C說話完成選擇排序、直接拔出排序、冒泡排序的示例。本站提示廣大學習愛好者:(C說話完成選擇排序、直接拔出排序、冒泡排序的示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C說話完成選擇排序、直接拔出排序、冒泡排序的示例正文
選擇排序
選擇排序是一種簡略直不雅的排序算法,其焦點思惟是:遍歷數組,從未排序的序列中找到最小元素,將其放到已排序序列的末尾。
時光龐雜度:O(n^2)
穩固性 :不穩固
/*
* @brief selection sort
*/
void
selection_sort(int a[], int n)
{
int i, j, min, tmp;
for (i = 0; i < n - 1; ++i) {
min = i;
for (j = i+1; j < n; ++j) {
if (a[j] < a[min]) {
min = j;
}
}
if (min != i) {
tmp = a[min];
a[min] = a[i];
a[i] = tmp;
}
}
}
直接拔出排序
直接拔出排序是一種比擬輕易懂得的排序算法,其焦點思惟是遍歷數組,將數組中的元素逐一拔出到已排序序列中。
時光龐雜度:O(n^2)
穩固性:穩固
完成:
/* @brief insetion sort
* insert the new element to the sorted subarray
*/
void
insertion_sort(int a[], int n)
{
int i, j, num;
for (i = 1; i < n; ++i) {
num = a[i];
for (j = i - 1; j >= 0 && a[j] > num; --j)
a[j+1] = a[j];
a[j+1] = num;
}
}
冒泡排序
冒泡排序是最根本的排序算法之一,其焦點思惟是從後向前遍歷數組,比擬a[i]和a[i-1],假如a[i]比a[i-1]小,則將二者交流。如許一次遍歷以後,最小的元素位於數組最前,再對除最小元素外的子數組停止遍歷。停止n次(n數組元素個數)遍歷後即排好序。外層輪回為n次,內層輪回分離為n-1, n-2…1次。
時光龐雜度: O(n^2)
穩固性:穩固
完成:
/* @brief bubble sort
* move the smallest element to the front in every single loop
*/
void
bubble_sort(int a[], int n)
{
int i, j, tmp;
for (i = 0; i < n; ++i) {
for (j = n - 1; j > i; --j) {
if (a[j] < a[j-1]) {
tmp = a[j];
a[j] = a[j-1];
a[j-1] = tmp;
}
}
}
}