Bubble_Sort & Select_Sort

来源:互联网 发布:mac foobar2000 编辑:程序博客网 时间:2024/05/18 03:52

Please indicate the source if you want to reprint: http://blog.csdn.net/gaoxiangnumber1.
Bubble Sort: O(n2)
以从小到大排序举例:设数组长度为N。
1.比较相邻的前后二个数据,如果前面数据大于后面的数据,就将二个数据交换。
2.这样对数组的第0个数据到N-1个数据进行一次遍历后,最大的一个数据就“沉”到数组第N-1个位置。
3.N=N-1,如果N不为0就重复前面二步,否则排序完成。
Select Sort: O(n2)
从无序区选一个最小的元素直接放到有序区的最后。
设数组为a[0…n-1]。
1. 初始时,数组全为无序区为a[0..n-1]。令i=0
2. 在无序区a[i…n-1]中选取一个最小的元素,将其与a[i]交换。交换之后a[0…i]就形成了一个有序区。
3. i++并重复第二步直到i==n-1。排序完成。
Codes:

#include<iostream>using namespace std;void SelectSort(int sort_array[], int length);void BubbleSort(int sort_array[], int length);int main(){    cout << "SelectSort:\n";    int test_array1[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};    int test_array2[9] = {5, 0, -99, 3, 56, 7, 8, -55, 56};    int test_array3[10] = {-1, -8, 50, 4, 20, 0, 45, 9999, 520, 555555};    SelectSort(test_array1, 10);    SelectSort(test_array2, 9);    SelectSort(test_array3, 10);    cout << "test_array1:\n";    for(int index = 0; index < 10; index++)    {        cout << test_array1[index] << " ";    }    cout << "\ntest_array2:\n";    for(int index = 0; index < 9; index++)    {        cout << test_array2[index] << " ";    }    cout << "\ntest_array3:\n";    for(int index = 0; index < 10; index++)    {        cout << test_array3[index] << " ";    }    cout << endl;    cout << "BubbleSort:\n";    int test_array4[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};    int test_array5[9] = {5, 0, -99, 3, 56, 7, 8, -55, 56};    int test_array6[10] = {-1, -8, 50, 4, 20, 0, 45, 9999, 520, 555555};    BubbleSort(test_array4, 10);    BubbleSort(test_array5, 9);    BubbleSort(test_array6, 10);    cout << "test_array4:\n";    for(int index = 0; index < 10; index++)    {        cout << test_array4[index] << " ";    }    cout << "\ntest_array5:\n";    for(int index = 0; index < 9; index++)    {        cout << test_array5[index] << " ";    }    cout << "\ntest_array6:\n";    for(int index = 0; index < 10; index++)    {        cout << test_array6[index] << " ";    }    cout << endl;    return 0;}void SelectSort(int sort_array[], int length){    for(int index1 = 0; index1 < length; index1++)    {        int min_index = index1;        for(int index2 = index1; index2 < length; index2++)  // find the minimum element's index        {            if(sort_array[min_index] > sort_array[index2])            {                min_index = index2;            }        }        swap(sort_array[min_index], sort_array[index1]);  // exchange element    }}void BubbleSort(int sort_array[], int length){    for(int cnt = 0; cnt < length; cnt++)    {        for(int index = 1; index < length - cnt; index++)        {            if(sort_array[index - 1] > sort_array[index])            {                swap(sort_array[index - 1], sort_array[index]);            }        }    }}

Please indicate the source if you want to reprint: http://blog.csdn.net/gaoxiangnumber1.

0 0
原创粉丝点击