Skip to content

Commit 6871ca2

Browse files
committed
add sort algorithm
1 parent 5544356 commit 6871ca2

2 files changed

Lines changed: 87 additions & 0 deletions

File tree

Basic_Algorithm/Sort/bubble.c

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* =========================================================
3+
* Filename: bubble.c
4+
* Description:
5+
*
6+
* =========================================================
7+
*/
8+
#include <stdio.h>
9+
#include <stdbool.h>
10+
#define SWAP(x,y) do{int temp;temp = x; x = y;y = temp;}while(0)
11+
void bubbleSort(int arr[],int n);
12+
void printArray(int arr[],int n);
13+
int main()
14+
{
15+
int arr[] = {64, 34, 25, 12, 22, 11, 90};
16+
int n = sizeof(arr)/sizeof(arr[0]);
17+
bubbleSort(arr, n);
18+
printf("Sorted array: \n");
19+
printArray(arr, n);
20+
return 0;
21+
}
22+
void bubbleSort(int arr[],int n){
23+
int i,j;
24+
bool swaped;
25+
for(i = n-1 ; i > 0 ; i--){
26+
bool swaped = false;
27+
for(j = 0 ; j < i ;j++)
28+
if(arr[j] > arr[j+1]){
29+
SWAP(arr[j] , arr[j + 1]);
30+
swaped = true;
31+
}
32+
if(!swaped)
33+
break;
34+
}
35+
}
36+
void printArray(int arr[],int n){
37+
int i = 0;
38+
while(i < n){
39+
printf("%d%s",arr[i],(i == n-1)?"\n":" ");
40+
++i;
41+
}
42+
43+
}

Basic_Algorithm/Sort/selection.c

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
* =========================================================
3+
* Filename: selection.c
4+
* Description: 选择排序
5+
* Hints:
6+
The algorithm maintains two subarrays in a given array.
7+
1) The subarray which is already sorted.
8+
2) Remaining subarray which is unsorted.
9+
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
10+
*
11+
*
12+
* =========================================================
13+
*/
14+
#include <stdio.h>
15+
#define SWAP(x,y) do{int temp;temp = x;x = y; y = temp;}while(0)//排序函数少不了swap
16+
void selectionSort(int arr[],int n);
17+
void printArray(int arr[],int n);
18+
int main()
19+
{
20+
int arr[] = {64, 25, 12, 22, 11};
21+
int n = sizeof(arr)/sizeof(arr[0]);
22+
selectionSort(arr, n);
23+
printf("Sorted array: \n");
24+
printArray(arr, n);
25+
return 0;
26+
}
27+
28+
void selectionSort(int arr[],int n){
29+
int i,j;
30+
for(i = 0;i < n;i++){
31+
int min_index = i;
32+
for(j = i;j < n;j++)
33+
if(arr[j] < arr[min_index])
34+
min_index = j;
35+
SWAP(arr[i],arr[min_index]);
36+
}
37+
}
38+
void printArray(int arr[],int n){
39+
int i = 0;
40+
while(i < n){//别乱用 i++ < n
41+
printf("%d%s",arr[i],(i == n-1)?"\n":" ");
42+
++i;
43+
}
44+
}

0 commit comments

Comments
 (0)