冒泡、交换、选择排序

时间:2021-04-13 22:06:46

#include <stdio.h>


int main()

{

int array[] = {3, 4, 2, 6, 3, 7, 3, 8, 5};

int i, j, temp, num;

num = sizeof(array) / 4;

/* BubbleSort */

for (i = 1; i < num; i++) {

for (j = 0; j < num-i; j++) {

if (array[j] > array[j+1]) {

temp = array[j];

array[j] = array[j+1];

array[j+1] = temp;

}

}

}

printf("\nBubbleSort :");

for (i = 0; i < num; i++) {

printf("%d  ", array[i]);

}

/* ExchangeSort */

for (i = 0; i < num-1; i++) {

for (j = i+1; j < num; j++) {

if (array[i] > array[j]) {

temp = array[i];

array[i] = array[j];

array[j] = temp;

}

}

}

printf("\nExchangeSort :");

for (i = 0; i < num; i++) {

printf("%d  ", array[i]);

}

/* SelectSort */

int pos;

for(i = 0; i < num-1; i++) {

temp = array[i];

pos = i;

for (j = i+1; j < num; j++) {

if (temp > array[j]) {

temp = array[j];

pos = j;

}

}

array[pos] = array[i];

array[i] = temp;

}

printf("\nSelectSort :");

for (i = 0; i < num; i++) {

printf("%d  ", array[i]);

}

return 0;

}