归并排序
归并排序
class Solution {
public int reversePairs(int[] nums) {
merge(nums, 0, nums.length - 1);
return count;
}
public void merge(int[] nums, int left, int right) {
int mid = left + ((right - left) >> 1);
if (left < right) {
merge(nums, left, mid);
merge(nums, mid + 1, right);
mergeSort(nums, left, mid, right);
}
}
public void mergeSort(int[] nums, int left, int mid, int right) {
int[] temparr = new int[right - left + 1];
int index = 0;
int temp1 = left, temp2 = mid + 1;
while (temp1 <= mid && temp2 <= right) {
if (nums[temp1] <= nums[temp2]) {
temparr[index++] = nums[temp1++];
} else {
temparr[index++] = nums[temp2++];
}
}
while (temp1 <= mid) {
temparr[index++] = nums[temp1++];
}
while (temp2 <= right) {
temparr[index++] = nums[temp2++];
}
for (int k = 0; k < temparr.length; k++) {
nums[k + left] = temparr[k];
}
}
}
堆排序
堆排序
import java.util.Arrays;
public class HeapSort {
public static void main(String[] args) {
int[] array = {4,6,1,2,9,8,3,5};
heapSort(array);
System.out.println(Arrays.toString(array));
}
public static void heapSort(int[] arr){
for (int i = arr.length/2-1; i >= 0 ; i--) {
adjustHeap(arr,i,arr.length);
}
for (int j = arr.length-1; j > 0; j--) {
int temp = arr[j];
arr[j] = arr[0];
arr[0] = temp;
adjustHeap(arr,0,j);
}
}
public static void adjustHeap (int[] arr,int i,int length){
int temp = arr[i];
for (int j = i * 2 + 1; j < length ; j = j * 2 + 1) {
if (j+1 < length && arr[j] < arr[j+1]){
j++;
}
if (arr[j] > temp){
arr[i] = arr[j];
i = j;
}else{
break;
}
}
arr[i] = temp;
}
}
快速排序
快排
package Sort;
public class 快速排序 {
public static void main(String[] args) {
int[] arr = {6,1,2,7,9,3,4,5,10,8};
sort(arr, 0, arr.length-1);
print(arr);
}
public static void sort(int[] arr,int leftBound,int rightBound) {
if(leftBound >= rightBound) return;
int mid= partition(arr, leftBound, rightBound);
sort(arr, leftBound, mid-1);
sort(arr, mid+1, rightBound);
}
static int partition(int[] arr, int leftBound,int rightBound) {
int pivot = arr[rightBound];
int left = leftBound;
int right = rightBound - 1;
while (left <= right) {
while(left <= right && arr[left] <= pivot) left++;
while(left <= right && arr[right] > pivot) right--;
if (left < right) {
swap(arr, left, right);
}
}
swap(arr, left, rightBound);
return left;
}
static void swap(int[] arr,int i,int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}