一、冒泡排序(Bubble Sort):
算法步骤:
1、比较相邻的第一个和第二个数,如果第一个比第二个大,相互交换
2、继续比较后边每一个相邻元素,从第一个到最后一个,使得这次排序后最后一个是最大的。
3、重复步骤12,最后一个除外
4、重复步骤123,直到结束。
算法图解:

代码实现:
public static void main(String[] args) {
int arr[] = {3,6,8,5,5,7,4,1,9,2,8};
for (int i = 0; i arr[j+1]){
int temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
结果输出:[1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 9]
二、选择排序(Selection Sort):
算法步骤:
1、在未排序的序列中寻找最小(最大)的数,放到第一个位置
2、重复第一步,将找到的最小(最大)的数,放到未排序序列的第一个位置。
3、重复上面的步骤,直到排序完成。
算法图解:

代码实现:
public static void main(String[] args) {
int arr[] = {3,6,8,5,5,7,4,1,9,2,8};
for (int i = 0; i
结果输出:[1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 9]
三、插入排序(Insertion Sort):
算法步骤:
1、将序列的第一个元素认为已经排过序了,从下一个元素开始;
2、将下一个元素取出,与后往前的向以排过序的元素比较,如果已排序的这个数比取出的数要大,则将这个已排序的数向后移一位。
3、重复第二步,取出的元素继续往前比较,直到找到找到已排序的元素比它小,将取出的数插入该位置后边
4、重复上面的步骤,直到排序完成。
算法图解:

代码实现:
public static void main(String[] args) {
int arr[] = {3,6,8,5,5,7,4,1,9,2,8};
for (int i = 1; i =0 && getOut
结果输出:[1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 9]
四、快速排序(QuickSort)
算法步骤:
1、从序列中随机选择一个数当作基准(一般选择第一个数)
2、重新排列顺序,将所有比基准小的数排在基准左边,所有比基准大的数放在基准的右边(相同的数可以放在任意一边)这时基准就将数列分为两块区域,左边的都比它小,右边的都比它大
3、通过递归将基准左边和右边的序列分别再次重复上面的操作,直到数列排序完成。
算法图解:

代码实现:
public static void main(String[] args) {
int arr[] = {3,6,8,5,5,7,4,1,9,2,8};
quickSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr,int start,int end){
if (start>=end){
return;
}
int pivot = arr[start];//将第一个值作为基准
int left = start;
int right = end;
while (left=pivot){
right--;
}
arr[left] = arr[right];
while (left
结果输出:[1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 9]
在上面四种排序中,冒泡排序是最经典的排序方法,但是效率比较低,快速排序的效率在这几种排序里面是最快的。
【信息由网络或者个人提供,如有涉及版权请联系COOY资源网邮箱处理】
暂无评论内容