排序算法:
#include <iostream> //冒泡排序 void bubbleSort(int array[],int size){ std::cout << "array= " << array << std::endl; for (int end = size-1; end > 0; end--) { for (int begin = 1; begin <= end; begin++) { if (array[begin] < array[begin-1]) { int tmp = array[begin]; array[begin] = array[begin-1]; array[begin-1] = tmp; } } } for(int i = 0; i < size; ++i) { printf("%d ", array[i]); } } //优化1(如果序列已经完全有序,可以提前终止冒泡排序) void bubbleSort1(int array[],int size){ std::cout << "array= " << array << std::endl; for (int end = size-1; end > 0; end--) { bool sorted = true; for (int begin = 1; begin <= end; begin++) { if (array[begin] < array[begin-1]) { int tmp = array[begin]; array[begin] = array[begin-1]; array[begin-1] = tmp; sorted = false; } } if (sorted == true) { break; } } for(int i = 0; i < size; ++i) { printf("%d ", array[i]); } } //优化2(如果序列尾部已经局部有序,可以记录最后1次交换的位置,减少比较次数) void bubbleSort3(int array[],int size){ std::cout << "array= " << array << std::endl; for (int end = size-1; end > 0; end--) { int sortedIndex = 1; for (int begin = 1; begin <= end; begin++) { if (array[begin] < array[begin-1]) { int tmp = array[begin]; array[begin] = array[begin-1]; array[begin-1] = tmp; sortedIndex = begin; } } end = sortedIndex; } for(int i = 0; i < size; ++i) { printf("%d ", array[i]); } } //选择排序 void selectionSort(int array[],int size){ for (int end = size-1; end > 0; end--) { int maxIndex = 0; for (int begin = 1; begin <= end; begin++) { if (array[maxIndex] < array[begin]) {//假定的这个数小于循环扫描的数 maxIndex = begin; } } int tmp = array[maxIndex]; array[maxIndex] = array[end]; array[end] = tmp; } for(int i = 0; i < size; ++i) { printf("%d ", array[i]); } }
相关学习地址:
https://visualgo.net/zh 图形化算法