1.简单选择排序
1.1. 示例
初始状态:57 68 59 52
第一步最小值为52,与第一个交换
52 68 59
57
第二步最小值为57,与第二个交换
52 57 59
68
第三步最小值为59,无需交换
52 57 59
68
完成状态:52 57 59 68
1.2. 基本思想
在要排序的一组数中,选出最小的数与第一个位置的数交换,然后在剩下的数当中再找最小的数与第二个位置的数交换,如此循环到最后一个数。
1.3. java代码
package com.zh218.com;
public class SelectSort
{
public static void main(String[] args) {
int a[] = {1,56,52,56,67,85,13,63,897};
int p = 0;
for (int i = 0; i < a.length; i++)
{
int j = i + 1;
p = i;
int temp = a[i];
for(; j<a.length;j++) {
if (a[j] < temp) {
temp = a[j];
p = j;
}
}
a[p] = a[i];
a[i] = temp;
}
for(int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}
2.冒泡排序
2.1 示例
初始状态:
57 68 59 52
第一步:57 68
59 52 -> 57 68
52 59
57 68
52 59 -> 57
52 68 59
57
52 68 59 -> 52 57 68 59
第二步: 52 57 68 59 -> 52 57
59 68
完成状态 52 57 59 68
2.2 基本思想
在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的数往上冒。即:每当两相邻的数比较后发现他们的排序与排序要求相反时,就将他们互换。
2.3 java代码
package com.zh218.com;
public class BubbleSort
{
public static void main(String[] args) {
int a[] = {21,41,21,45,56,2,15,634,647,122,67,234,7687,14,45,78,96,97,06,35,234,45,24,5,2525};
int temp = 0;
for (int i = 0; i < a.length-1; i++)
{
for (int j = 0; j < a.length-1; j++)
{
if (a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for (int i = 0; i < a.length; i++)
{
System.out.println(a[i]);
}
}
}
3.插入排序
3.1 示例
初始状态:57 68 59 52
第一步57 68 59 52 68>57, 不处理
第二步57 68 59 52 57<59<68, 59插在57之后
第三步57 59 68 52 52<57, 插在52之后
完成状态:52 57 59 68
3.2 基本思想
在要排序的一组数中,假设前面(n-1)[n>=2]个数已经排好顺序,现在要把第n个数插到前面的有序数中,使得这n个数也是排好顺序的。如此反复循环,直至全部数排好顺序。
3.3 代码
package com.zh218.com;
public class InsertSort
{
public static void main (String[] args) {
int a[] = {56,89,45,68,87,96,47,78,96,61,21,32,47,62};
int temp = 0;
for (int i = 1; i < a.length; i++)
{
int j = i - 1;
temp = a[i];
for (; j>=0&&temp<a[j];j--)
{
a[j+1] = a[j]; //将大于temp的值整体后移一个单位
}
a[j+1] = temp;
}
for(int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
转载请注明原文地址: https://ju.6miu.com/read-1301120.html