Bubble Sort
ALGORITHM
Bubble sort is often our first contact with a sorting algorithm, so the idea is relatively simple, it works by index (arrays, collections, etc.) order from front to back and turn it back to compare the elements one by one.
Analysis of Algorithms
Code
public static void bubleSort(Integer[] arr){
for(int i=0;i<arr.length-1;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
Selection Sort
ALGORITHM
Select sort core idea is to find the elements to be sorted from the smallest element, we can put a set of data is divided into two parts, the left is a good row, row of the right is not good. Initially, the whole is not sorted before, we assume that at this time arr[0]
, that is minIndex=0
, the position of the element is minimal. Then we turn to the back of the elements and compare it, if arr [j] than this arr[minIndex]
even smaller, then we update minIndex
-> minIndex=j
value, after the end of the last round of the loop, if i
not equal minIndex
, we will carry out exchange operations. Then i = 1, minIndex = i, the next round of operation.
Analysis of Algorithms
Code
public static void selectSort2(Integer[] arr){
for(int i=0;i<arr.length-1;i++){
int minIndex = i;
for(int j=i+1;j<arr.length;j++){
if(arr[minIndex]>arr[j]){
minIndex=j;
}
}
if(minIndex!=i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
Insertion Sort
ALGORITHM
For insertion sort, we can sort it with the selection ratio, both of which sort we can be divided into two parts, had been properly arranged (left), no row good (on the right). Selection Sort is selected from the smallest never properly arranged array, the index is based on the order of insertion sort out element, then moving (typically moved forward from the rear) has been sorted array.
Ideas analysis
Conventional insertion sort code for:
public void sort(Comparable[] arr){
for(int i=1;i<arr.length;i++){ //外循环
for(int j=i;j>0;j--){ //内循环
if(arr[j].compareTo(arr[j-1])<0){
Comparable temp = arr[j-1];
arr[j-1]=arr[j];
arr[j]=temp;
}
else{
break; ,
}
}
}
}
After insertion sort optimized to achieve
public void sort2(Comparable[] arr){
for(int i=1;i<arr.length;i++){
Comparable e=arr[i];
int j;
for(j=i;j>0;j--) {
if(arr[j-1].compareTo(e)>0){
arr[j]=arr[j-1];
}else{
arr[j]=e;
break;
}
}
}
}