How to call the quick sort function to sort data in Java requires specific code examples
Quick sort is a commonly used sorting algorithm when processing large-scale data Has higher efficiency. Calling the quick sort function in Java to sort data can be implemented recursively. The following will introduce you in detail how to perform quick sorting in Java and provide specific code examples.
First of all, we need to understand the principle of quick sort. The basic idea of quick sort is to select a benchmark element and divide the sequence to be sorted into two parts through one sorting pass. The elements in one part are smaller than the benchmark element, and the elements in the other part are larger than the benchmark element. The two parts are then sorted recursively until the entire sequence is sorted.
The following is a quick sort code example in Java:
public class QuickSort { public void quickSort(int[] arr, int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } public int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } public static void main(String[] args) { int[] arr = {10, 7, 8, 9, 1, 5}; int n = arr.length; QuickSort sorter = new QuickSort(); sorter.quickSort(arr, 0, n - 1); System.out.println("排好序的数组:"); for (int i : arr) { System.out.print(i + " "); } } }
In the above example, we first define a QuickSort class and declare the quickSort and partition methods in it. The quick sort method quickSort uses a recursive method to divide the array into two parts by calling the partition method, and then continue to call the quickSort method recursively on the two parts until the entire array is sorted. The partition method is used to determine the base element and place elements smaller than the base element to the left of the base element and elements larger than the base element to the right of the base element.
In the main method, we create an array arr containing some unsorted elements and pass it to the quickSort method for sorting. Finally, we use a loop to print out the sorted array.
Through the above code example, we can call the quick sort function in Java to sort data. You can modify and adjust this example to implement more complex sorting functionality based on your actual needs. Hope this article helps you!
The above is the detailed content of Write quick sort algorithm in Java to sort data. For more information, please follow other related articles on the PHP Chinese website!