排序算法

来源:互联网 发布:中国工业软件市场规模 编辑:程序博客网 时间:2024/06/08 10:29
1 冒泡排序int SortBubble(int* array,int size){if (NULL == array ||0 >= size) {    return 1;}for (int count = 1;count < size;count++) {for (int j = 0;j < size - count;j++) {if ( array[j] > array[j+1] ) {int tmp = array[j];array[j] = array[j+1];array[j+1] = tmp;}}}return 0;}2 选择排序int SortSelect(int* array, int size){if (NULL == array ||0 >= size) {    return 1;}for (int count = 1;count < size;count++) {int key = array[count - 1];for (int j = count;j < size;j++) {if ( array[j] < key) {int tmp = key;array[count - 1] = array[j];key = array[count - 1];array[j] = tmp;}}}return 0;}3 插入排序int SortInsert(int* array, int size){if (NULL == array ||0 >= size) {    return 1;}//Consider the first element is sorted,then start from the second element to insert.int start = 0;for(int i = start + 1;i < size;i++){int cur = array[i];int j = i - 1;//Compare the current element to insert with the sorted elements which start from the last element of current element.while((j >= start) &&   (array[j] > cur)) {array[j+1] = array[j]; j--;}array[j+1] = cur;}return 0;}4 快速排序int SortQuick(int* array, int size){    if (NULL == array) {        return 1;    }    if (2 > size) return 1;    int start = 0;    int end = size - 1;    int key = array[start];    while (start < end) { //Divide the unsorted part into smaller and bigger parts based on key value until start = end         while (start < end) {            if (array[end] < key) {                array[start] = array[end]; //After this statement, array[end] is empty. The element with bigger index than end must be bigger than key.                start++;//The unsorted area is from start++ to end now.                break;            }            end--;        }        //If code can reach here, then either array[end] is empty or start=end.        //If array[end] is empty, then sort the area from start to end based on key.        while(start < end) {            if (array[start] > key) {                array[end] = array[start];                end--;//The unsorted area is from start to end-- now.                break;            }            start++;        }    }    //start must be EQUAL to end and array[start] is empty now,then assign the key value to it.    array[start] = key;    SortQuick(array, start);    SortQuick(array+start+1, size - start - 1);    return 0;}      


0 0
原创粉丝点击