冒泡排序
源码实现
package csdn.dreamzuora.sort;
import java.util.List;
public class BubbleSort extends Sort<Integer>{
@Override
public void sort(List<Integer> array) {
if (array == null || array.isEmpty()){
return;
}
int size = array.size();
for (int i = 0; i < size - 1; i++){
for (int j = 0; j < size - 1; j++){
if (array.get(j) > array.get(j + 1)){
int temp = array.get(j + 1);
array.set(j + 1, array.get(j));
array.set(j, temp);
}
}
}
}
}
单元测试
package csdn.dreamzuora.sort;
import com.sun.deploy.util.StringUtils;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class BubbleSortTest {
BubbleSort bubbleSort = new BubbleSort();
@Test
public void sort() {
List<Integer> sortList = Arrays.asList(3, 5, 4, 0, 1);
List<Integer> expectList = Arrays.asList(0, 1, 3, 4, 5);
bubbleSort.sort(sortList);
Assertions.assertEquals(expectList, sortList);
}
}
优化
package csdn.dreamzuora.sort;
import java.util.List;
public class BubbleSortPlus extends Sort<Integer>{
@Override
public void sort(List<Integer> array) {
if (array == null || array.isEmpty()){
return;
}
int size = array.size();
for (int i = 0; i < size - 1; i++){
boolean isSort = true;
for (int j = 0; j < size - 1; j++){
if (array.get(j) > array.get(j + 1)){
isSort = false;
int temp = array.get(j + 1);
array.set(j + 1, array.get(j));
array.set(j, temp);
}
}
if (isSort){
break;
}
}
}
}
快速排序
源码实现
package csdn.dreamzuora.sort;
import java.util.List;
public class QuickSort extends Sort<Integer> {
@Override
public void sort(List<Integer> a, int left, int right) {
if (left >= right){
return;
}
int value = a.get(left);
int i = left;
int j = right;
while (left < right){
while (right != left && a.get(right) >= value){
right --;
}
while (left != right && a.get(left) <= value){
left ++;
}
if (left == right){
a.set(i, a.get(left));
a.set(left, value);
sort(a, i, left - 1);
sort(a, left + 1, j);
}
else {
int temp = a.get(left);
a.set(left, a.get(right));
a.set(right, temp);
}
}
}
public void sort2(List<Integer> array){
}
}
单元测试
package csdn.dreamzuora.sort;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class QuickSortTest {
QuickSort quickSort = new QuickSort();
@Test
public void sort() {
List<Integer> list = Arrays.asList(5, 8, 6, 3, 9, 2, 1, 7);
quickSort.sort(list, 0, list.size() - 1);
System.out.println(list);
}
}