java bubble sort and quicksort code

  • 2020-06-19 10:11:31
  • OfStack

Bubble sort:

Basic idea: In the 1 group of Numbers to be sorted, compare and adjust the two adjacent Numbers from top to bottom for all the Numbers in the range not yet sorted, so that the larger number will sink and the smaller number will rise. That is, whenever two adjacent Numbers are compared and find that their order is the opposite of the order requirement, they are interchanged.


public class BubbleSorted{ 
public BubbleSorted(){ 
int a[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51}; 
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]); 
} }

Quicksort:

Algorithm: When the data volume is very large, it is suitable to use this method. When using the two-point method, the data should be ordered and not repeated. Basic idea: Suppose the data is sorted in ascending order. For the given value x, the comparison starts from the middle position of the sequence. If the current position value is equal to x, the search is successful. If x is less than the current position value, it is searched in the first half of the sequence; If x is greater than the current position value, the search continues in the second half of the sequence until it is found.

Suppose there is an array {12, 23, 34, 45, 56, 67, 77, 89, 90}, it is required to use the 2-point method to find the specified value and return it in the index of the array. If it is not found, it will return -1. 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;
}
}

Related articles: