您的位置:首页 > 其它

直接选择排序

2015-11-30 16:53 387 查看
面试基础问题:直接选择排序

每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序地放在已排好序的数列的最后,直到全部待排序的数据元素排完。

例如:

初始数组资源: [63 4 24 1 3 15 ]

第一趟排序后: [15 4 24 1 3 ] 63

第二趟排序后: [15 4 3 1] 24 63

package com;

public class MyTest {

public static void main(String[] args) {

int[] array = { 63, 4, 24, 1, 3, 15 };
//BubbleSort(array);
SelectSort(array);
print(array);
}

/**
* 冒泡排序
*
* @param array
*/
public static void BubbleSort(int[] array) {
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < array.length - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}

/**
* 直接选择排序
* @param array
*/
public static void SelectSort(int[] array) {
int index;
for (int i = 1; i < array.length; i++) {
index = 0;
for (int j = 1; j <= array.length - i; j++) {
if (array[j] > array[index])
index = j;
}
int temp = array[array.length - i];
array[array.length - i] = array[index];
array[index] = temp;
}
}

/**
* 打印方法
*
* @param array
*/
public static void print(int[] array) {
for (int k : array) {
System.out.print(k + "<");
}
}

}


理解:直接找出最大的数据和最后的数据交换
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: