Whenever the interview to avoid talking about the topic is the sorting algorithm, the last interview was asked to write sorting algorithm, and then the head of a Meng will not write, mercilessly was the interviewer despised, asked if I was the first time to participate in the interview, how can not even sort algorithm? But it was really the first time to go to the interview, with this evil-fill sorting algorithm.
First, the basic sorting algorithm: The basic sorting algorithm has bubble sort, select sort, insert sort.
- Select Sort algorithm idea: Select sort start with the head of the array, compare the first element to the other elements, find the smallest element, and place it in the first position of the array. Then from the second element to find a smaller element than his, put in the second position, and so on, and so on, repeat the above steps, when the second position of the array, the completion of the sort.
The code is as follows:
functionSelectionsort (arr) {vark, temp; for(vari = 0; i < arr.length-1; i++) { varMin =i; for(varj = i + 1; J < Arr.length; J + +) { if(Arr[min] >Arr[j]) {min=J; } } if(min! =i) {temp=Arr[min]; Arr[min]=Arr[i]; Arr[i]=temp; } } returnarr; }
Analysis: The outer loop represents the move from the first element of the array to the second-to-last element, the inner loop from the second element to the final element, looking for a position that is smaller than the element pointed to by the current outer loop, records the subscript for the smallest value after each iteration of the loop, and swaps the value that the outer loop points to. Swap the smallest value in the array to the appropriate location. The time complexity of this can be introduced as: O (n*n). means that in the case of N is small, the algorithm can guarantee a certain speed, when n is large enough, the efficiency of the algorithm will be reduced. And with the increase of N, the time of the algorithm grows rapidly. Therefore, special attention should be paid to the use. Wait for the next chapter to see the bubble sort.
Sorting algorithm summary------Select Sort---javascript description