sort code

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  void mySwap(int arr[],int place)
{
	int temp=arr[place];
	arr[0]=arr[place];
	arr[place]=temp;
}
void f(int arr[],int len)
{
	int j;
	for(j=0;j<len;j++)
		if(arr[j]>arr[j+1])
			mySwap(arr,j+1);
}
void mySort(int arr[],int len)
{
	int k;
	for(k=0;k<len;k++)
		f(arr,k);
}



how can i fix it to sort upwise 0 1 2 3 4


i realy want to do it my own i just didn't understand why the swap looks like it is
(apparantly it doesn't do any swap)

another thing is how to it sort?!
Last edited on
Lets look at one thing first:
1
2
3
4
5
6
void mySwap(int arr[],int place)
{
	int temp=arr[place];
	arr[0]=arr[place];
	arr[place]=temp;
}

The line 4 does not change temp or arr[place], so lets pretend that the line is not there:
1
2
3
4
5
void mySwap(int arr[],int place)
{
	int temp = arr[place];
	arr[place] = temp;
}

That does ... nothing. Lets remove that and return the line 4:
1
2
3
4
void mySwap(int arr[],int place)
{
	arr[0] = arr[place];
}

That is not "swap". That simply copies some element to position 0. Always to 0. The original value is lost.

Swap has to retain all information. That is why a proper swap does a "safe copy" (the 'temp') from one element (A). Then that element A is overwritten with the value of element B. The original value of A is still in temp, while both elements (A and B) have the value of B. The last step is to restore the value from temp to element B.


However, even if your swap would swap, it could only swap the first element with something. Lets have an example array:
2 5 3 // we should swap 5 and 3, but we cannot
// swap 5
5 2 3
// swap 3
3 2 5
// swap 2
2 3 5

There is no way that you want to do that. What if you could swap place1 and place2, rather than 0 and place?
Topic archived. No new replies allowed.