简单选择排序和直接插入排序

#include <iostream>
using namespace std;

//直接插入排序
//    int A[10] = {0, 3, 1, 5, -1, 2, 7, 3, 4, 10};
void insertSort(int A[], int n) {
    for (int i = 1; i < n; i++) {
        int temp = A[i];
        for (int j = i-1; j >= 0; j--) {
            if (temp < A[j]) {

                A[j+1] = A[j];

                if (j == 0) {
                    A[j] = temp;
                }
            } else {
                A[j+1] = temp;
                break;
            }
        }

    }
}


void selectSort(int A[], int n) {
    for (int i = 0; i < n; i++) {
        int min = i;
        for (int j = i+1; j < n; j++) {
            if (A[min] > A[j]) {
                min = j;
            }
        }
        int temp = A[min];
        A[min] = A[i];
        A[i] = temp;
    }
}

int main() {
    int A[10] = {0, 3, 1, 5, -1, 2, 7, 3, 4, 10};
    int B[10] = {0, 3, 1, 5, -1, 2, 7, 3, 4, 10};

    selectSort(A, sizeof(A)/sizeof(A[0]));
    insertSort(B, sizeof(B)/sizeof(B[0]));

    for (int i = 0; i < sizeof(A)/sizeof(A[0]); i++) {
        cout << A[i] << " ";
    }
    cout << endl;

    for (int i = 0; i < sizeof(B)/sizeof(B[0]); i++) {
        cout << B[i] << " ";
    }
    cout << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_32273417/article/details/86695860
今日推荐