I have created a sorting function. Can I know the name of this algorithm? Is this bubble sort?
I am new in C.
#include <stdio.h>
void sort(int *, int);
int main(void) {
int arrayNum[] = {1, 12, 8, 4, 90, 11, 76};
int len = sizeof(arrayNum) / sizeof(arrayNum[0]);
sort(arrayNum, len);
for (int i = 0; i < len; i ) {
printf("%d, ", arrayNum[i]);
}
return 0;
}
void sort(int *array, int length) {
int temp;
for (int i = 0; i < length; i ) {
for (int j = 0; j < length; j ) {
if (array[i] < array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
CodePudding user response:
I don't think it has a name, but it's described in this paper: "Is this the simplest (and most surprising) sorting algorithm ever?" Stanley P. Y. Fung
CodePudding user response:
No it's not bubble sort. It doesn't compare adjacent elements nor implements any check to stop traversing if the array becomes sorted.
It's similar to exchange sort, which could be implemented like the following (note the differences, though):
for (int i = 0; i < length; i ) {
// At every step, searches the minimum of the remaining elements
for (int j = i 1; j < length; j ) {
// ^^^^^ It doesn't touch the already sorted
if ( array[j] < array[i] ) {
// ^^^ ^^^ To sort the array in ascending order
/* swap array[j] and array[i] */
}
}
}
I'd argue that the posted algorithm is much more similar to insertion sort. See how it transforms the array:
Starting point 1, 12, 8, 4, 90, 11, 76 Swaps 1 with 12 and then 12 with 90. 90, 1, 8, 4, 12, 11, 76 Swaps 90 with 1. 1, 90, 8, 4, 12, 11, 76 Swaps 90 and 8. In other words, it "inserts" 8 in an already sorted partition. 1, 8, 90, 4, 12, 11, 76 Inserts 4 (it first swaps 8 and 4, then 90 and 8). 1, 4, 8, 90, 12, 11, 76 Inserts 12 (swaps 90 and 12). 1, 4, 8, 12, 90, 11, 76 Inserts 11 (swaps 12 and 11, then 90 and 11). 1, 4, 8, 11, 12, 90, 76 Inserts 76 (swaps 90 and 76), then ends. 1, 4, 8, 11, 12, 76, 90