冒泡排序
重复走访要排序的数列,比较相邻两个元素,如果顺序错误就交换,直到该数列无需再交换为止。
升序冒泡
void BubbleSorting(int arr[], int len) { if (len < 1) throw "Param is wrong. Length is not correct."; if (len == 1) return; int temp; for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - 1 - i; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } show(arr, 6); } }
降序冒泡(导论)
void BubbleSorting2(int arr[], int len) { if (len < 1) throw "Param is wrong. Length is not correct."; if (len == 1) return; int temp; for (int i = 0; i < len - 1; i++) { for (int j = len - 1; j > i; j--) { if (arr[j] < arr[j - 1]) { temp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = temp; } } show(arr, 6); } }
测试代码:
int main() { int a[] = { 1, 4, 2, 7, 10, 5 }; //insertion_sort_asc(a, 6); //insertion_sort_asc_with_while(a, 6); //insertion_sort_des(a, 6); //MergeSorting2(a, 0, 5); BubbleSorting(a, 6); return 0; }
结果:
时间: 2024-10-22 01:57:21