JAVA排序算法实现代码-选择(Select)式排序
-
-
-
-
-
-
- public class Test {
- public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 };
-
- public static void main(String args[]) {
- int i;
- int Index = a.length;
-
- System.out.print("排序前: ");
- for (i = 0; i < Index - 1; i++)
- System.out.printf("%3s", a[i]);
- System.out.println("");
-
- SelectSort(Index - 1);
-
- System.out.print("排序后: ");
- for (i = 0; i < Index - 1; i++)
- System.out.printf("%3s", a[i]);
- System.out.println("");
- }
-
- public static void SelectSort(int Index) {
- int i, j, k;
- int MinValue;
- int IndexMin;
- int Temp;
-
- for (i = 0; i < Index - 1; i++) {
- MinValue = 32767;
- IndexMin = 0;
- for (j = i; j < Index; j++) {
- if (a[j] < MinValue)
- {
- MinValue = a[j];
- IndexMin = j;
- }
- Temp = a[i];
- a[i] = a[IndexMin];
- a[IndexMin] = Temp;
- }
-
- System.out.print("排序中: ");
- for (k = 0; k < Index; k++)
- System.out.printf("%3s", a[k]);
- System.out.println("");
- }
- }
- }
/**
* JAVA排序算法实现代码-选择(Select)式排序。
*
* @author 老紫竹 JAVA世纪网(java2000.net)
*
*/
public class Test {
public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // 预设数据数组
public static void main(String args[]) {
int i; // 循环计数变量
int Index = a.length;// 数据索引变量
System.out.print("排序前: ");
for (i = 0; i < Index - 1; i++)
System.out.printf("%3s", a[i]);
System.out.println("");
SelectSort(Index - 1); // 选择排序
// 排序后结果
System.out.print("排序后: ");
for (i = 0; i < Index - 1; i++)
System.out.printf("%3s", a[i]);
System.out.println("");
}
public static void SelectSort(int Index) {
int i, j, k; // 循环计数变量
int MinValue; // 最小值变量
int IndexMin; // 最小值索引变量
int Temp; // 暂存变量
for (i = 0; i < Index - 1; i++) {
MinValue = 32767; // 目前最小数值
IndexMin = 0; // 储存最小数值的索引值
for (j = i; j < Index; j++) {
if (a[j] < MinValue) // 找到最小值
{
MinValue = a[j]; // 储存最小值
IndexMin = j;
}
Temp = a[i]; // 交换两数值
a[i] = a[IndexMin];
a[IndexMin] = Temp;
}
System.out.print("排序中: ");
for (k = 0; k < Index; k++)
System.out.printf("%3s", a[k]);
System.out.println("");
}
}
}
运行结果
排序前: 10 32 1 9 5 7 12 0 4
排序中: 1 32 10 9 5 7 12 0 4
排序中: 1 5 32 10 9 7 12 0 4
排序中: 1 5 9 32 10 7 12 0 4
排序中: 1 5 9 10 32 7 12 0 4
排序中: 1 5 9 10 32 7 12 0 4
排序中: 1 5 9 10 32 7 12 0 4
排序中: 1 5 9 10 32 7 12 0 4
排序中: 1 5 9 10 32 7 12 0 4
排序后: 1 5 9 10 32 7 12 0 4