选择排序和插入排序

来源:互联网 发布:米格29知乎 编辑:程序博客网 时间:2024/05/22 01:37

选择排序:

       选择排序算法首先找到列表中最大元素,将其放置在列表末尾。然后在剩余元素中求最大元,将其放置在列表次末尾,依次类推,直至列表只剩下一个元素为止。

void selectionSort(double list[], int arraySize){for (int i = arraySize-1; i >= 0; i--){double currentMax = list[0];int currentMaxIndex = 0;for (int j = 1; j <= i; j++){if (list[j] > currentMax){currentMax = list[j];currentMaxIndex = j;}}if (currentMaxIndex != i){list[currentMaxIndex] = list[i];list[i] = currentMax;}}}


插入排序:

        反复地将一个新元素插入到一个已排序的子列表中,直至整个列表排序完毕。

void insertionSort(double list[], int arraySize){for (int i = 1; i < arraySize; i++){double currentElement = list[i];int k;for (k = i-1; k >= 0 && list[k] > currentElement; k--)list[k+1] = list[k];list[k+1] = currentElement;}}


 

 

原创粉丝点击