我已经实现了一个代码来使用选择排序对该数组进行排序。代码看起来没问题,但它并没有完美地对数组进行排序。这是要排序的数组,{20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2}
这是我实现的代码;
public class Main {
public static void main(String[] args) {
int[] arr = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2};
System.out.println("Unsorted Array: \t");
StringBuffer sb = new StringBuffer();
for (Object s : arr) {
sb.append(s);
sb.append(" ");
}
String str = sb.toString();
System.out.println(str);
selectionSort(arr);
System.out.println("Sorted Array: \t");
printArray(arr);
}
public static void selectionSort(int[] arr) {
int n = arr.length;
// one by one move boundary of unsorted subarray
for (int i = 0; i < n - 1; i++) {
// find the minimum element in unsorted array
int min = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min]) {
min = j;
}
//swapping the found min value with the first element
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}
public static void printArray(int[] arr) {
StringBuffer sb = new StringBuffer();
for (Object s : arr) {
sb.append(s);
sb.append(" ");
}
String str = sb.toString();
System.out.println(str);
}
}
这是我收到的输出;
我不知道为什么它没有正确排序,很想得到一些帮助。
交换发生在内部循环之后。就像,
public static void selectionSort(int[] arr) {
int n = arr.length;
// one by one move boundary of unsorted subarray
for (int i = 0; i < n - 1; i++) {
// find the minimum element in unsorted array
int min = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
// swapping the found min value with the first element
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
只需更改它(并添加 printArray
)我就明白了
Unsorted Array:
[20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2]
Sorted Array:
[2, 5, 6, 7, 14, 17, 19, 20, 22, 39, 42, 46, 47, 48, 51]
class selecion_sort{
static void selection(int[] arr){
for (int i=0;i<arr.length-1;++i){
//initialise the element to a variable named 'key' and traverse the element
//using another for loop and compare the the smallest number among the elements
//of the array....
int key=i;
for (int j=i+1;j<arr.length;++j){
if (arr[key]>arr[j]){
key=j;
}
}
//swap the smallest element with the first element and as the iteration grows
//the swapping continues as 1st,2nd,3rd elements.......
int temp=arr[key];
arr[key]=arr[i];
arr[i]=temp;
}
}
//this method prints the elements of an array.....
static void print(int[] arr){
for (int i=0;i<arr.length;++i){
System.out.print(" "+arr[i]);
}
}
public static void main(String[] args){
int[] arr={23,54,65,12,87,45,10,45};
selection(arr);
print(arr);
}
}