Java Bubble sorting and quick sorting code, java Bubble Sorting
Bubble Sorting:
Basic Idea: In the number of a group to be sorted, compare and adjust the two adjacent numbers from top to bottom based on the total number in the range not sorted yet, let a large number sink, a small number rises. That is, when the numbers of two adjacent parties are compared and their sorting and sorting requirements are opposite, they are exchanged.
Public class BubbleSorted {
Public BubbleSorted (){
Int a [] = };
Int temp = 0;
For (int I = 0; I <a. length-1; I ++ ){
For (int j = 0; j <a. length-1-i; j ++ ){
If (a [j]> a [j + 1]) {
Temp = a [j];
A [j] = a [j + 1];
A [j + 1] = temp;
}
}
}
For (int I = 0; I <a. length; I ++)
System. out. println (a [I]);
}}
Quick sorting:
Algorithm: This method is suitable when the data volume is large. When binary search is used, data must be ordered and not repeated. Basic Idea: assume that the data is sorted in ascending order. For the given value x, the comparison starts from the intermediate position of the sequence. If the current position is equal to x, the search is successful; if x is smaller than the current position value, it will be searched in the first half of the series; if x is greater than the current position value, it will continue searching in the second half of the series until it is found.
Suppose there is an array {12, 23, 34, 45, 56, 67, 77, 89, 90 }, now we need to use the binary method to find the specified value and return it to the index of the array. If no value is found,-1 is returned. The Code is as follows:
Package com. test;
Public class FindSorted {
Public static void main (String [] args ){
Int [] arr = new int [] {12, 23, 34, 45, 56, 67, 77, 89, 90 };
System. out. println (search (arr, 12 ));
System. out. println (search (arr, 45 ));
System. out. println (search (arr, 67 ));
System. out. println (search (arr, 89 ));
System. out. println (search (arr, 99 ));
}
Public static int search (int [] arr, int key ){
Int start = 0;
Int end = arr. length-1;
While (start <= end ){
Int middle = (start + end)/2;
If (key <arr [middle]) {
End = middle-1;
} Else if (key> arr [middle]) {
Start = middle + 1;
} Else {
Return middle;
}
}
Return-1;
}
}