Typical for loop Cases
Because the for loop can change the traversal interval by controlling the initial values and the ending condition of the loop variable, it is relatively simple to use the for loop during sorting or traversing, the following are my summary cases.
1. Application of sorting
1) Exchange sorting:Compare the number retrieved with the remaining number after the number position, place the largest or smallest number first in a group, and then place the second number in the second place, sort all the numbers in sequence.
1 for(int i = 0; i < (num.length - 1); i ++) 2 { 3 for(int j = i + 1; j < num.length; j ++) 4 { 5 if(num[i] > num[j]) 6 { 7 int temp = num[j]; 8 num[i] = num[j]; 9 num[j] = temp;10 }11 }12 }
The code above is to find the minimum value in the array num from I-num. length, and there is the first position, where num is an array that stores a large amount of data.
2) Bubble Sorting:By constantly comparing the size of two adjacent numbers, a large number is constantly switched to the next position, and a small number floats to the top position of the array.
1 for (int I = nums. length-1; I> 0; I --) 2 {3 // sink the maximum number in the range to I 4 for (int j = 0; j <I; j ++) 5 {6 if (nums [j]> nums [j + 1]) 7 {8 // exchange 9 int temp = nums [j]; 10 nums [j] = nums [j + 1]; 11 nums [j + 1] = temp; 12} 13} 14}
3) Select sorting:The minimum number in a range is raised to the first value in the range by means of exchange sorting.
1 for (int I = 0; I <nums. length-1; I ++) 2 {3 int index = I; // first assume that the subscript of the minimum number is I 4 for (int j = I + 1; j <nums. length; j ++) 5 {6 if (nums [j] <nums [index]) 7 {8 index = j; 9} 10} 11 int temp = nums [I]; 12 nums [I] = nums [index]; 13 nums [index] = temp; 14}
2. Determination of prime numbers
1 bool isFinnd = false; 2 for (int I = 2; I <num; I ++) 3 {4 if (num % I = 0) 5 {6 isFinnd = true; 7 break; // when a number I is found to be able to fully divide num, it indicates that the current num is a sum, end the current for loop 8} 9} 10 if (! IsFinnd) // If num is a prime number, the error code 11 {12 // determines that the current num is a prime number 13}
The num of the current Code is a specific integer variable.
In addition to the above cases, there are also many application scenarios that need to be summarized by everyone.