冒泡排序不是对所有元素进行排序



关于下面的冒泡排序算法,我有一个小问题。我在VS中运行,但它没有给我排序的输出,它只是交换了数组中第二个和最后一个元素的位置。有人能调查一下并调试一下吗?

import java.util.Arrays;
public class Arraysort {

static void sort(int[] array) {
int n = array.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n-i); j++) {
if (array[j-1] > array[i]) {
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
public static void main(String[] args){
int array[] = {2,6,7,9,5};

System.out.println("This is my unsorted Arrayn");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
System.out.println();
}
sort(array);
System.out.println("This is my sorted Arrayn");
for(int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
}
}

输出是:25796

这是因为您使用了j范围1到n-i。这里的问题是当你使用1到(n-i)时,它会跳过一个列表的检查周期。你需要做的就是运行n次(j <N),以确保您遍历列表中的所有循环。>

change j <(n-i)到j <(n)

public class Arraysort {
static void sort(int[] array) {
int n = array.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n); j++) {
if (array[j - 1] > array[i]) {
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
}
public static void main(String[] args) {
int array[] = { 2, 6, 7, 9, 5 };
System.out.println("This is my unsorted Arrayn");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
System.out.println();
}
sort(array);
System.out.println("This is my sorted Arrayn");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
}
}

最新更新