排序算法

常见用的排序算法学习

1.冒泡排序

基本思想:两两比较待排序序列中的元素,并交换不满足顺序要求的各对元素,直到全部满足顺序要求为止。

C代码:

void bubble_sort(int arr[],int n)

{

    int    j;

    while (n>0)

    {

        for (j = 0; j < n-1; j++)

        {

            if (arr[j]>arr[j + 1])

            {

                int temp = arr[j + 1];

                arr[j + 1] = arr[j];

                arr[j] = temp;

            }

        }

        n--;

    }

}

 2.直接插入排序

基本思想:每一步将一个待排序元素按其关键字值的大小插入到已排序序列的适当位置,直到将待排序元素插入完为止。

C代码:

void insertion_sort(int a[], int n)

{

    int i,j,temp;

    for (i = 1; i < n; i++)

    {

        j = i;

        temp = a[i];

        while (j > 0 && a[j-1]>temp)

        {

            a[j] = a[j - 1];

            j--;

        }

        a[j] = temp;

    }

}

 3.选择排序

基本思想:每次从待排序序列中选择一个关键字最小的元素,顺序排在已排序序列的最后,直至全部排完。

C代码:

void selection_sort(int a[], int n)

{

    int i, j,min_index,temp;

    for (i = 0; i< n - 1; i++)

    {

        min_index = i;

        for (j = i + 1; j < n; j++)

        {

            if (a[min_index]>a[j])

                min_index = j;

        }

        temp = a[i];

        a[i] = a[min_index];

        a[min_index] = temp;

    }

}

 

你可能感兴趣的:(排序算法)