欢迎关注微信公众号“Python小灶,和我一起每天学习Python新知识”
算法
排序
冒泡
#include <stdio.h>
void bubble_sort(int arr[], int len)
{
int i,j,temp;
for (i = 0; i < len - 1; i++) {
for ( j = 0; j < len - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
int arr[] = { 22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70 };
int len = (int) sizeof(arr)/sizeof(*arr);
bubble_sort(arr, len);
int i;
for ( i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
return 0;
}
选择
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int arr[] = { 22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70 };
// int arr[] = { 22, 34, 3 };
int len = (int) sizeof(arr)/sizeof(*arr);
int i,j;
for (i = 0; i < len - 1; i++) {
for (j = i + 1; j < len; j++) {
if (arr[j] < arr[i]) {
swap(&arr[j], &arr[i]);
}
}
}
for ( int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
return 0;
}