How can i do ascending sort in 4*4 array

May 26, 2008 at 3:59pm
how can i sort 4*4 array elements (ascending sort)
May 26, 2008 at 5:29pm
That depends on what you mean by "ascending sort" on a 2D array.
May 26, 2008 at 5:58pm
eg:
3 2 5 6
5 6 9 0
3 4 2 1
6 8 7 2

it must be:
0 1 2 2
2 3 3 4
5 5 6 6
6 7 8 9
May 26, 2008 at 6:49pm
I'd use an incremental sorting alg. Where you have your first marker, and increment a second marker from that to the end. Each time replacing the first marker with the second marker when the second marker is < the first marker. Once you hit the end of the array, increment the first marker.

The only problem with this method is that is takes N + N-1 + N-2 etc iterations. (e.g. 16 + 15 + 14)
May 28, 2008 at 8:14pm
All arrays are 1-dimensional. So you could access element array[1,0] by array[5].
Just threat the arrays as 1-dimesnional and shuffle it. I don't know whether some library has some sorting algoritmn but otherwise you could take a look on wikipedia for some sorting algoritmns.
May 29, 2008 at 6:09am
Hello

I wrote this one yesterday as a mental exercise during office-hours :)

It works fine.

regards

int main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void Sorting(int *pArray);

int main()
{
	// code to initialize Array and do what must be done

	int *pArray = Array;
	Sorting(pZahlen);

	// rest of code
}


void Sorting(int *pArray)
{
	bool Again = 1;
	int ClipBoard;
	while (Again)
	{
	Again = 0;
	for (int i =0;i<15;i++) 		// 
		{
		if (*(pArray+i) > *(pArray+i + 1)
			{
				ClipBoard = *(pArray+i);
				*(pArray+i) = *(pArray+i+1);
				*(pArray+i+1) = ClipBoard;
				Again = 1; 	
                                                }	
		}
	}
}
}
May 29, 2008 at 1:02pm
Although it would probably work it's not very fast.
Faster algoritmns are quicksort and selection sort.

I also recommend passing the number of elements of the array as a parameter, so you you also use it on arrays with a size other than 15.
In dorat's case:
4*4 = 16
May 29, 2008 at 1:22pm
@somelauiw

This code is for darat's case.
He has 16 figures in his array so the highest index in the array is 15.
So, in order to compare value 15 with value 16 the i in the loop has to be 14 (the 15th entry has index 14).

But you are right, it is definitely better to pass the size of the array or to calculate the size in order to get the proper for-loop.

regards

int main
May 29, 2008 at 6:37pm
Yes, it 15. Sorry, I wasn't carefully paying attention. Some algoritmns have to loop through the whole array.
You are using a variant of the Bubblesort algoritmn.

To calculate the number of values:
arraylen = sizeof(array)/sizeof(array[0])
May 30, 2008 at 5:43am
No offence taken :).

Nice to know that the thing I came up with has got such a nice name.

Enjoy your weekend

int main
Topic archived. No new replies allowed.