堆排序
java代码实现
package csdn.dreamzuora.sort;
import java.util.List;
public abstract class Sort<E> {
public void sort(List<E> array){
if (array == null || array.isEmpty()){
return;
}
};
public void sort(List<E> array, int left, int right){
};
}
package csdn.dreamzuora.sort;
import java.util.List;
public class HeapSort extends Sort<Integer>{
@Override
public void sort(List<Integer> array) {
for(int size = array.size(), i = size / 2 - 1; i >= 0; i--){
adjustHeap(array, i, size);
}
for (int j = array.size() - 1; j > 0; j--){
swap(array, 0, j);
adjustHeap(array, 0, j);
}
}
public void adjustHeap(List<Integer> arr, int i, int length){
int temp = arr.get(i);
for(int k = i*2 + 1; k < length; k = k*2 + 1){
if(k+1 < length && arr.get(k) < arr.get(k+1)){
k++;
}
if(arr.get(k) > temp){
arr.set(i, arr.get(k)) ;
i = k;
}else{
break;
}
}
arr.set(i, temp);
}
private void swap(List<Integer> arr, int a, int b){
int temp = arr.get(a);
arr.set(a, arr.get(b));
arr.set(b, temp);
}
}
单元测试
package csdn.dreamzuora.sort;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class HeapSortTest {
@Test
public void sort() {
HeapSort heapSort = new HeapSort();
List<Integer> list = Arrays.asList(4, 5, 2, 6);
heapSort.sort(list);
Assertions.assertEquals(Arrays.asList(2, 4, 5, 6), list);
}
}
归并排序
java代码实现
package csdn.dreamzuora.sort;
import java.util.ArrayList;
import java.util.List;
public class MergeSort extends Sort<Integer>{
@Override
public void sort(List<Integer> a) {
if (a == null || a.isEmpty()){
return;
}
List<Integer> b = new ArrayList<>();
for (int i = 0; i < a.size(); i++){
b.add(0);
}
merge(a, b,0, a.size());
for (int i = 0; i < b.size(); i++){
a.set(i, b.get(i));
}
}
private void merge(List<Integer> a, List<Integer> b, int start, int end){
if (end - start <= 1){
return;
}
int mid = (start + end)/2;
int left = start;
int right = mid;
int index = start;
merge(a, b, start, mid);
merge(a, b, mid, end);
while (left < mid || right < end){
if (right >= end){
b.set(index ++, a.get(left ++));
}
else if (left < mid && a.get(left) < a.get(right)){
b.set(index ++, a.get(left ++));
}
else {
b.set(index ++, a.get(right ++));
}
}
for (int i = start; i < index; i++){
a.set(i, b.get(i));
}
}
}
单元测试
package csdn.dreamzuora.sort;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import java.util.*;
import static org.junit.Assert.*;
public class MergeSortTest {
@Test
public void sort() {
MergeSort mergeSort = new MergeSort();
Random random = new Random();
List<Integer> actuallyList = Arrays.asList(random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100));
List<Integer> expectList = new ArrayList<>(actuallyList);
Collections.sort(expectList);
mergeSort.sort(actuallyList);
Assertions.assertEquals(expectList, actuallyList);
}
}