Question about selection sort

closed account (zwpL3TCk)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void Sort(int array[], int size) // Function to sort array selection
{
    for(int i = 0; i < size; i++)
    {
        for(int j = i+ 1; j < size; j++) // What is use of this and
	{                                // and the below codes
	    if(array[j] < array[i])
	    {
	        int temp = array[i]; 
		array[i] = array[j];
		array[j] = temp;
	    }
	}
    }
}
Last edited on

for(int j = i+ 1; j < size; j++) // What is use of this and

This loop just checks every integer in array[] greater than i

for example if i is 0 then the loop will check for j = i+ 1 ie 1 and 2 and 3 and so on and on untill j < size
then
i will become 1 and j will be 2 and 3 and so on.....

1
2
3
4
5
6
7
{                                // and the below codes
	    if(array[j] < array[i])
	    {
	        int temp = array[i]; 
		array[i] = array[j];
		array[j] = temp;
	    }


This code is just swapping the values of a and b. It is using a var (temp) to temporarily store the value and then replace it

like if a=3 and b=5 then after this code a=5 and b=3

Hope it helps

Last edited on
Topic archived. No new replies allowed.