簡單選擇排序(Simple Selection Sort)
阿新 • • 發佈:2018-06-16
enc main as2 gdt knn tns bof pll n+1
簡單選擇排序(Simple Selection Sort):相比較冒泡排序,每次都是兩兩比較交換,n個元素n-1次比較可以確定1個元素的最終位置。簡單選擇排序法就是通過n-i次關鍵字的比較,從n-i+1個記錄中選出關鍵字最小的記錄,並和第i(1≤i≤n)個記錄交換。
#include<iostream> using namespace std; void swap(int& elem1,int& elem2) { int tmp = elem1; elem1 = elem2; elem2 = tmp; } int simpleSelectionSort(int* arr,int length) { if(NULL==arr||length<=0) return -1; int minPos = 0; for(int idx=0;idx!=length;++idx) { minPos = idx; for(int iidx=idx+1;iidx<length;++iidx) { if(arr[iidx]<arr[minPos]) { minPos = iidx; } } if(idx!=minPos) { swap(arr[idx],arr[minPos]); } } return 0; } | void printArr(int* arr,int length) { if(NULL==arr||length<=0) return ; for(int idx=0;idx!=length;++idx) { cout<<arr[idx]<<" "; } cout<<endl; } void test() { int arr[] = {6,5,3,1,8,7,2,4}; printArr(arr,8); simpleSelectionSort(arr,8); printArr(arr,8); cout<<endl; int arr1[] = {1,2,3,4,5,6,7,8}; printArr(arr1,8); simpleSelectionSort(arr1,8); printArr(arr1,8); cout<<endl; int arr2[] = {2,2,2,2}; printArr(arr2,4); simpleSelectionSort(arr2,4); printArr(arr2,4); cout<<endl; int arr3[] = {2,2,1,2}; printArr(arr3,4); simpleSelectionSort(arr3,4); printArr(arr3,4); cout<<endl; int* arr4 = NULL; printArr(arr4,4); simpleSelectionSort(arr4,4); printArr(arr4,4); cout<<endl; } int main() { test(); system("pause"); } |
簡單選擇排序(Simple Selection Sort)