排序

穩定:若是a本來在b前面,而a=b,排序以後a仍然在b的前面;
不穩定:若是a本來在b的前面,而a=b,排序以後a可能會出如今b的後面;
內排序:全部排序操做都在內存中完成;
外排序:因爲數據太大,所以把數據放在磁盤中,而排序經過磁盤和內存的數據傳輸才能進行;
時間複雜度: 一個算法執行所耗費的時間。
空間複雜度:運行完一個程序所需內存的大小。算法

排序code

int a[] = {10,9,8,7,6,5,4,3,2,1};
int count = sizeof(a)/sizeof(int);

選擇排序排序

for (int i = 0; i < count; i++) {
        int minIndex = i;//從第一個位置開始
        for (int j =i+1 ; j <count; j++) {
            if (a[minIndex] > a[j]) {
                minIndex = j; // 找到剩餘數中最小數的索引
            }
        }
        // 交換
        int temp = a[i];
        a[i] = a[minIndex];
        a[minIndex] = temp;
    }

冒泡排序索引

for (int i = 0; i < count; i++) {
        for (int j = 0; j < count-1-i; j++) {
            if (a[j]>a[j+1]) {
                int temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
            }
        }
    }

快速排序內存

void swap(int arr[], int low, int high) {
        if (low == high) {
            return;
        }
        int temp;
        temp = arr[low];
        arr[low] = arr[high];
        arr[high] = temp;
    }

    int findPartition(int arr[], int low, int high){
        int base = arr[low];
        while (low<high) {
            while (low<high && arr[high]>=base) {
                high--;
            }
            swap(arr, low, high);
            while (low<high && arr[low]<=base) {
                low++;
            }
            swap(arr, low, high);
        }
        return low;
    }
    
    void QS(int arr[], int low, int high) {
        if (low<high) {
            int base = findPartition(arr,low,high);
            QS(arr, low, base-1);
            QS(arr, base+1, high);
        }
    }
相關文章
相關標籤/搜索