Case 1.

  • Enter a random group of numbers and arrange them in ascending order.

Analysis: sort is the most common algorithm, this time using bubble sort algorithm to achieve. The specific implementation code is as follows:

#include <stdio.h> #define N 3 int main() { int nums[N]; // define an array int I, j; // loop variable int temp; Printf (" Please enter %d number: ",N); for(i = 0; i < N; i++) { scanf("%d",&nums[i]); } // for(I = 0; i < N - 1; I++) {// for(j = 0; j < N - i - 1; If (nums[j] > nums[j + 1]) {temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; }}} printf("\n "); for(i = 0; i < N; i++) { printf("%d\t", nums[i]); } return 0; }Copy the code
  • The effect picture is as follows:

2. Think about

Core code:

For (I = 0; i < N - 1; I++) {// for(j = 0; j < N - i - 1; If (nums[j] > nums[j + 1]) {temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; }}}Copy the code
  • Nums [j] > nums[j + 1]; Compare two adjacent numbers and swap if the current is larger than the latter. At the end of each round of sorting, pick the largest unsorted number and place it at the end of the array, and so on. Nums [j] < nums[j] < nums[j + 1]
  • Another commonly used algorithm is swapping:
  • temp = nums[j];
  • nums[j] = nums[j + 1];
  • nums[j + 1] = temp;
  • Swapping the values of two variables requires introducing a temporary variable, just like swapping two glasses of water with an empty glass, which is exactly the same as the example of pouring water, and you can think of it in the same way.
  • Above is a simple bubble sort method, we can according to the example, thank you!