简体   繁体   中英

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 dummified selection sort - it matches the description of selection sort on Wikipedia:

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

But indeed not the pseudo algorithm in that it does some unnecessary swaps.

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;
        }
    }
}

What it does different from ordinary selection sort is that it makes unnecessary swaps back and forth from the i th place. The ordinary selection sort finds the minimum index and does only one swap for each element:

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

    tmp = data[min];
    data[min] = data[i];
    data[i] = tmp;
}

Nevertheless, the original matches the description of selection sort (and the running time is the same, though constants are worse due to unnecessary swapping) in that:

The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order)

is realized as the algorithm finds the smallest element in the unsorted sublist, exchanging the current smallest item with the leftmost unsorted item as it goes over the list .


The C standard library already contains qsort which can be used instead of reinventing the wheel - we just need to write the comparison function:

#include <stdlib.h>

int compare_ints(const void *a, const void *b) 
{
    return (*(const int*)a - *(const int*)b);
}

int main(void) {
    ...
    qsort(data, MAX, sizeof(int), compare_ints);
    ...
}

No it wouldn't loop because you'll just swap the data[i] with data[i] twice although it is better to rewrite this piece of code like this :

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

but this two code are same.

the algorithm that this codes are using is bubble sort . If you want to have better understanding of what it does take a look at the wikipedia article.

This is a Bubble Sort . The gist of it is that it swaps any two adjacent values that it finds out of order, until all of the values are in order.

The code

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;
            }
        }
    }

Will clearly not work as it is supposed to. It basically needs to compare each and every element of the array and sorts them. Basically a bubble sort with time complexity O(n^2).

Rather than j=i

It should be j=i+1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM