方法一:通过冒泡排序的思想
#include <stdio.h> void add_num(int* arr, int n, int m) { arr[n] = m; int i = 0; int j = 0; for (i = 0; i <= n-1; i++) { for (j = 0; j <= n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; } } } for (i = 0; i <= n; i++) { printf("%d ",arr[i]); } } int main() { int n = 0; int arr[50] = { 0 }; int i = 0; scanf("%d",&n); for (i = 0; i < n; i++) { scanf("%d",&arr[i]); } int m = 0; scanf("%d",&m); add_num(arr, n, m); return 0; }方法二:
#include <stdio.h> int main() { int arr[20] = { 0 }; int n = 0; int i = 0; int tmp = 0; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } int m = 0; scanf("%d", &m); for (i = n-1; i >=0; i--) { if (m < arr[i]) { arr[i + 1] = arr[i]; arr[i] = m; //arr[i] = arr[i + 1]; } else break; } arr[i + 1] = m; for (int i = 0;i <= n;i++) { printf("%d ", arr[i]); } }