GordanAndrews -4 years ago 115
C Question

# C Basic Sort Algorithm

I'm not really understanding the process behind this basic sorting algorithm using nested For loops:

``````for(i=0; i<MAX; i++){
for(j=i; j<MAX; j++){
if(data[i] > data[j]){
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
}
``````

If
`j=i`
then wouldn't it just be looping and comparing the same numbers seeing as i and j both start at 0 in the loops?

I've tried googling for an explanation on this particular bit of code and can't find anything useful.

Full program:

``````#include <stdio.h>
#include <stdlib.h>

#define MAX 10

int main()
{
int data[MAX];
int i, j, tmp;

for(i=0;i<MAX;i++){
printf("Enter number %d: ", i);
scanf("%d", &data[i]);
}

for(i=0; i<MAX; i++){
for(j=i; j<MAX; j++){
if(data[i] > data[j]){
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
}

printf("\nSorted List:\n");
for(i=0;i<MAX;i++){
printf("Item %d: %d\n", i, data[i]);
}
}
``````

This algorithm is a simple selection sort.

In the first inner round, with `i` being equal to `j`, the comparison `data[i] > data[j]` will be false, and the swap will not be executed.

Then, `j` will be incremented, and now it is comparing `i`th value with `i + 1`th value.

To avoid one futile comparison, initialize `j` with `i + 1`:

``````for (i = 0; i < MAX; i++) {
for (j = i + 1; j < MAX; j++) {
if (data[i] > data[j]) {
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download