數(shù)據(jù)結(jié)構(gòu)與算法 排序(冒泡,選擇,插入)
數(shù)據(jù)結(jié)構(gòu)與算法 排序(冒泡,選擇,插入)
1.冒泡排序
1.1算法
冒泡排序(buddle-sort)算法的運作如下:(從后往前)
比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
對每一對相鄰元素作同樣的工作,從開始第一對到結(jié)尾的最后一對。在這一點,最后的元素應該會是最大的數(shù)。
針對所有的元素重復以上的步驟,除了最后一個。
持續(xù)每次對越來越少的元素重復上面的步驟,直到?jīng)]有任何一對數(shù)字需要比較。
1.2 實現(xiàn)
//
// main.c
// BubbleSort
//
// Created by Wuyixin on 2017/6/2.
// Copyright © 2017年 Coding365. All rights reserved.
//
#include <stdio.h>
void bubbleSort(int a[],int n){
int i,j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i; j++) {
if (a[j] > a[j + 1]){
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
int main(int argc, const char * argv[]) {
int a[] = {9,3,1,4,7,6,5,8,2};
bubbleSort(a, 9);
int i = 0;
while (i < 9)
printf("%d ",a[i++]);
return 0;
}
2.選擇排序
2.1 算法
選擇排序(selection-sort)是一種簡單直觀的排序算法。它的工作原理是每一次從待排序的數(shù)據(jù)元素中選出最?。ɑ蜃畲螅┑囊粋€元素,存放在序列的起始位置,直到全部待排序的數(shù)據(jù)元素排完
2.2實現(xiàn)
//
// main.c
// SelectionSort
//
// Created by Wuyixin on 2017/6/2.
// Copyright © 2017年 Coding365. All rights reserved.
//
#include <stdio.h>
void selectionSort(int a[],int n){
int i,j,min,temp;
for (i = 0; i < n; i++) {
min = i;
for (j = i + 1; j < n; j++) {
if (a[j] < a[min])
min = j;
}
if (i != min){
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
}
int main(int argc, const char * argv[]) {
int a[] = {9,3,1,4,7,6,5,8,2};
selectionSort(a, 9);
int i = 0;
while (i < 9)
printf("%d ",a[i++]);
return 0;
}
3.插入排序
3.1 算法
插入排序(insertion-sort)的基本思想是:每步將一個待排序的紀錄,按其關(guān)鍵碼值的大小插入前面已經(jīng)排序的文件中適當位置上,直到全部插入完為止。
3.2 實現(xiàn)
//
// main.c
// InsertionSort
//
// Created by Wuyixin on 2017/6/2.
// Copyright © 2017年 Coding365. All rights reserved.
//
#include <stdio.h>
void insertionSort(int a[],int n){
int i,j,temp;
for (i = 1; i < n ; i++) {
temp = a[i];
for (j = i; j > 0 && temp < a[j - 1]; j--) {
a[j] = a[j - 1];
}
a[j] = temp;
}
}
int main(int argc, const char * argv[]) {
int a[] = {9,3,1,4,7,6,5,8,2};
insertionSort(a, 9);
int i = 0;
while (i < 9)
printf("%d ",a[i++]);
return 0;
}
以上就是對C語言數(shù)據(jù)結(jié)構(gòu)與算法中排序的講解,大家如有疑問可以留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Vscode Remote Development遠程開發(fā)調(diào)試的實現(xiàn)思路
這篇文章主要介紹了Vscode Remote Development遠程開發(fā)調(diào)試的相關(guān)資料,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04

