【演算法】氣泡排序與選擇排序的遞迴實現
阿新 • • 發佈:2019-02-18
1 氣泡排序
1 氣泡排序: void bubbleSort(int *data,int start,int end) { if (start < end) { int temp = 0; int length = end - start + 1; for (int i = start; i < length - 1; i ++) { if (data[i] < data[i + 1]) { temp = data[i]; data[i] = data[i + 1]; data[i + 1] = temp; } } end --; bubbleSort(data,start,end); } } 注意問題:end--那裡,注意每次遞迴的起始終止下標的移動,起始下標不變,終止下標每次減1, 迴圈結束條件 為start == end,以及i < length - 1;
2 選擇排序
void selectionSort(int *data,int start,int end) { if (start < end) { //int length = end - start + 1; int temp = data[start]; int index = start; for (int i = start + 1; i < end + 1; i ++) { if (data[index] > data[i]) { index = i; } } for (int i = 0; i < 10; i ++) { printf("%d ",data[i]); } printf("\n"); if (start != index) { temp = data[start]; data[start] = data[index]; data[index] = temp; } start ++; selectionSort(data, start, end); } } 注意問題:start ++那裡,注意每次遞迴的起始終止下標的移動,起始每次加1,終止下標不變, 迴圈結束條件 為start == end,以及i < end + 1