LGG bubble sort OK
(高顯忠, sjgau4311@gmail.com, 2010-12-24 14:11)
1樓
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
#define SWAP(x, y) { int t; t= x; x= y; y= t; }
void selectionSort(int[]); // 選擇排序
void insertionSort(int[]); // 插入排序
void bubbleSort(int[]); // 氣泡排序
void show_data(int number[])
{
int i;
printf("\n");
for (i=0;i<MAX;i++) {
printf("%3d, ", number[i]);
}
printf("\n");
system("pause");
}
int main(void) {
srand(time(NULL));
printf("排序前:");
int number[MAX] = {0};
int i;
for(i = 0; i < MAX; i++) {
number[i] = rand() % 100;
printf("%d ", number[i]);
}
printf("\n請選擇排序方式:\n");
printf("(1)選擇排序\n(2)插入排序\n(3)氣泡排序\n:");
scanf("%d", &i);
switch(i) {
case 1: selectionSort(number); break;
case 2: insertionSort(number); break;
case 3: bubbleSort(number); break;
default: printf("選項錯誤(1..3)\n");
}
int k;
for(k = 0; k < MAX; k++)
printf("%d ", number[k]);
printf("\n");
return 0;
}
void selectionSort(int number[]) {
int i;
for(i = 0; i < MAX-1; i++) {
int m = i;
int j;
for(j = i+1; j < MAX; j++)
if(number[j] < number[m])
m = j;
if(i != m)
SWAP(number[i], number[m])
}
}
void insertionSort(int number[]) {
int j;
for(j = 1; j < MAX; j++) {
int tmp = number[j];
int i = j - 1;
while(tmp < number[i]) {
number[i+1] = number[i];
i--;
if(i == -1)
break;
}
number[i+1] = tmp;
}
}
void bubbleSort(int number[]) {
int flag = 1;
int i;
for(i = 0; i < MAX-1 && flag == 1; i++) {
printf("i= %d\n", i);
flag = 0;
int j;
for(j = 0; j < MAX-i-1; j++) {
if(number[j+1] < number[j]) {
printf("swap the number of number[j]= %d, number[j+1]= %d\n",
number[j], number[j+1]);
SWAP(number[j+1], number[j]);
flag = 1;
}
}
show_data(number);
}
printf("\n\n\n *** end of sort\n");
}