1. 程式人生 > >資料結構與演算法: 排序1

資料結構與演算法: 排序1

1 氣泡排序

2 選擇排序

3 插入排序

 

 

#include <iostream>
#include <vector>

using namespace std;
class Solution
{
public:
    //氣泡排序
    void bubble_sort(vector<int> &array) {
        int all = array.size();
        if (array.empty() != 0 || all <2){//all == 0
            return;
        }
        for (int end = all -1; end > 0; end--)//end--
            for (int i = 0 ; i < end ; i++ ){
                if ( array[i] > array[i+1] ) {//前面大於後面的就交換
                    //swap(array,i ,i+1);
                   int temp = array[i];
                   array[i] = array[i+1];
                   array[i+1] = temp;
            }
        }
        /*for(int i=0; i < array.size(); ++i) {
            cout << array[i] << endl;
        }*/

    }

    //選擇排序
    void selection_sort(vector<int> &array) {
        int all = array.size();
        if (array.empty() != 0 || all <2){//all == 0
            return;
        }
        for (int i = 0; i < all; i++){
            int mindex = i;//定義放i步最小值的位置
            for (int j = i + 1; j < all; j++){
                mindex = array[j] < array[mindex] ? j :mindex;
            }//i位置後邊的數與它比較
            int temp = array[i];
            array[i] = array[mindex];
            array[mindex] = temp;

        }



    }


    //插入排序
    void Insection_sort(vector<int> &array) {
        int all = array.size();
        if (all == 0 && all<2){
            return;
        }
        for (int i = 1; i < all; i++){
            for (int j = i - 1; j >= 0; j--) {//i的前邊的數開始
                if(array[j] > array[j+1]){//前邊的數比後邊的數大交換
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;

                }
            }

        }

    }








private:
    /*void swap(int array, int i, int j ){
        if (array[i] > array[j]){
            int temp = array[j];
            array[j] = array[i];
            array[i] = temp;

        }
    }*/
};

int main()
{
    int a1[]={ 7, 2, 8, 9, 6, 5, 3, 0, 12,5,2};

    vector<int> array(a1,a1+11);
    for(int i = 0;i < array.size(); ++i) {
        cout << array[i] << endl;
    }
    cout << "after" << endl;
    Solution solu;
    //solu.bubble_sort(array);

    solu.selection_sort(array);
    //solu.Insection_sort(array);




    for(int i = 0;i < array.size(); ++i) {
        cout << array[i] << endl;
    }

    return 0;
}