直接插入排序(Straight Insertion Sort)
阿新 • • 發佈:2018-06-16
mes pat consola data 排序 lsd eqv vpd pub
直接插入排序(Straight Insertion Sort):將一個記錄插入到已經排好序的有序表中,從而得到一個新的、記錄數增1的有序表。
#include<iostream> using namespace std; void swap(int& elem1,int& elem2) { int tmp = elem1; elem1 = elem2; elem2 = tmp; } int straightInsertionSort(int* arr,int length) { if(NULL==arr||length<=0) return -1; for(int idx=1;idx!=length;++idx) { //把後面的第idx個元素插入到前面的有序數組0~idx-1中 int tmp = arr[idx]; int behindIdx = idx - 1; while(behindIdx>=0&&arr[behindIdx]>tmp) { arr[behindIdx+1] = arr[behindIdx]; --behindIdx; } arr[++behindIdx] = tmp; } 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); straightInsertionSort(arr,8); printArr(arr,8); cout<<endl; int arr1[] = {1,2,3,4,5,6,7,8}; printArr(arr1,8); straightInsertionSort(arr1,8); printArr(arr1,8); cout<<endl; int arr2[] = {2,2,2,2}; printArr(arr2,4); straightInsertionSort(arr2,4); printArr(arr2,4); cout<<endl; int arr3[] = {2,2,1,2}; printArr(arr3,4); straightInsertionSort(arr3,4); printArr(arr3,4); cout<<endl; int* arr4 = NULL; printArr(arr4,4); straightInsertionSort(arr4,4); printArr(arr4,4); cout<<endl; } int main() { test(); system("pause"); } |
直接插入排序(Straight Insertion Sort)