bubblesort
两个for循环,从最右端开始一个一个逐渐有序
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void bubble(int *arr, int len);
int main(int argc, char *argv[])
{
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int len = sizeof(arr) / sizeof(int);
bubble(arr, len);
for (int i = 0; i < len; i++)
{
printf("%d ", arr[i]);
}
putchar(10);
return 0;
}
void bubble(int *arr, int len)
{
for (int i = 0; i < len - 1; i++)
{
int count = 0;
for (int j = 0; j < len - 1 - i; j++)
{
if (arr[j] < arr[j + 1])
{
arr[j] ^= arr[j + 1];
arr[j + 1] ^= arr[j];
arr[j] ^= arr[j + 1];
count++;
}
}
if (count == 0)
{
break;
}
}
}
selectsort
假设是升序,两个for循环,从最左端开始一个一个逐渐有序,找到lengh-1个无序区的最小值
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void selectSort(int *arr, int len);
int main(int argc, char *argv[])
{
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int len = sizeof(arr) / sizeof(int);
selectSort(arr, len);
for (int i = 0; i < len; i++)
{
printf("%d ", arr[i]);
}
putchar(10);
return 0;
}
void selectSort(int *arr, int len)
{
int i, j;
int min;
for (i = 0; i < len - 1; i++)
{
min = i;
for (j = i + 1; j < len; j++)
{
if (arr[j] > arr[min])
{
min = j;
}
}
if (i != min)
{
arr[min] ^= arr[i];
arr[i] ^= arr[min];
arr[min] ^= arr[i];
}
}
}
insertsort
两个for循环,从最左端开始一个一个逐渐有序,默认第一个就是有序区,第一个for遍历无序区,第二个for循环遍历有序区,为无序区的元素的插入挪出合适的位置
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void insertSort(int *arr, int len)
{
int i, j;
int temp;
for (i = 1; i < len; i++)
{
temp = arr[i];
for (j = i - 1; j >= 0; j--)
{
if (arr[j] > temp)
{
arr[j + 1] = arr[j];
}
else
{
break;
}
}
arr[j + 1] = temp;
}
}
int main(int argc, char *argv[])
{
int arr[] = {11, 2, 3, 4, 5, 6, 7};
int len = sizeof(arr) / sizeof(int);
insertSort(arr, len);
for (int i = 0; i < len; i++)
{
printf("%d ", arr[i]);
}
putchar(10);
return 0;
}
quicksort
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int oneSort(int *arr, int low, int high)
{
int key = arr[low];
while (low < high)
{
while (low < high && arr[high] >= key)
{
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= key)
{
low++;
}
arr[high] = arr[low];
}
arr[low] = key;
return low;
}
void quickSort(int *arr, int low, int high)
{
if (low >= high)
{
return;
}
int mid = oneSort(arr, low, high);
oneSort(arr, low, mid - 1);
oneSort(arr, mid + 1, high);
}
int main(int argc, char *argv[])
{
int arr[] = {11, 2, 3, 4, 5, 6, 1};
int len = sizeof(arr) / sizeof(int);
quickSort(arr, 0, len - 1);
for (int i = 0; i < len; i++)
{
printf("%d ", arr[i]);
}
putchar(10);
return 0;
}
脑图
#!/bin/bash
function fun()
{
read -p "请输入用户名:" username
str=`grep -w $username /etc/passwd`
if [ -n "$str" ]
then
echo `id -u $username`
echo `id -g $username`
else
echo "用户不存在"
fi
}
arr=(`fun`)
echo ${arr[*]}