Preface: About the Bubble sort and choose the sort, each time writes the time to look at their concept again, this time, writes oneself to understand1. Bubble Sort:
In fact, bubble sort should be proved by example, set the array length to n.
1. Compare the next two data, if the previous data is larger than the data, two data will be exchanged.
2. So that the No. 0 data of the array to N-1 data after one traversal, the largest one of the data is "sink" to the N-1 position of the array.
3. N=n-1, if N is not 0, repeat the previous two steps, otherwise the sort is complete.
Look at the basic method, just write a code to verify
1 //2. Bubble sort2 @Test3 Public voidtest2 () {4 int[] arr={14,9,8,15,34,5};5 intTemp=0;6 for(inti=0;i<arr.length;i++){7 for(intj=0;j<arr.length-1;j++){8 if(arr[j]>arr[j+1]){9temp=Arr[j];TenArr[j]=arr[j+1]; Onearr[j+1]=temp; A } - } - } the - //The traverse output has three kinds of output way, can refer to my blog 3 in the way of traversing output - for(intA:arr) { - System.out.println (a); + } -}
Operating effect:
2. Select Sort:
Thought: First find the smallest in all the sequences and then put it in the first position. Then look at the smallest of the remaining elements and put them in the second position ... And so on, you can do the whole sort of work.
Code:
1 @Test2 Public voidtest4 () {3 int[] arr = {14, 9, 8, 90, 34, 5,78 };4 intMinindex;5 inttemp;6 for(inti = 0; i < arr.length-1; i++) {7minindex=i;8 for(intj = i + 1; J < Arr.length; J + +) {9 if(Arr[j] <Arr[minindex]) {TenMinindex =J; One } A } - if(minindex!=i) { -temp=Arr[i]; thearr[i]=Arr[minindex]; -arr[minindex]=temp; - } - } + for(intI:arr) { - System.out.println (i); + } A at}
Operating effect:
Bubble sort and select Sort (Classic edition)----Java Basics Summary