Java气泡排序
我试图创建一个冒泡排序,但我发现我的代码有问题。输出为:82345679。我希望是:23456789Java气泡排序,java,Java,我试图创建一个冒泡排序,但我发现我的代码有问题。输出为:82345679。我希望是:23456789 package com.company; public class Main { public static void main(String[] args) { // write your code here int[] tab = {9,8,7,6,5,4,3,2}; int[] result = {9,8,7,6,5,4,3,2
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
int[] tab = {9,8,7,6,5,4,3,2};
int[] result = {9,8,7,6,5,4,3,2};
for (int i = 0; i < result.length; i++ ) {
if (i < result.length - 1 ) {
if (result[i] > result[i+1]) {
result = permute(result, i);
i = 0;
}
}
}
for (int i: result) {
System.out.print(i);
}
}
public static int[] permute (int[] tableau, int index) {
int temp;
temp = tableau[index];
tableau[index] = tableau[index+1];
tableau[index+1] = temp;
return tableau;
}
}
package.com公司;
公共班机{
公共静态void main(字符串[]args){
//在这里编写代码
int[]tab={9,8,7,6,5,4,3,2};
int[]result={9,8,7,6,5,4,3,2};
for(int i=0;i结果[i+1]){
结果=排列(结果,i);
i=0;
}
}
}
for(int i:结果){
系统输出打印(一);
}
}
公共静态int[]置换(int[]表,int索引){
内部温度;
温度=表[索引];
表[索引]=表[索引+1];
表[索引+1]=温度;
返回表;
}
}
您需要两个循环
int swap;
for (int i = 0; i < ( result.length - 1 ); i++) {
for (int j = 0; j < result.length - 1; j++) {
if (result[j] > result[j+1]) {
swap = result[j];
result[j] = result[j+1];
result[j+1] = swap;
}
}
}
int交换;
对于(int i=0;i<(result.length-1);i++){
对于(int j=0;j结果[j+1]){
交换=结果[j];
结果[j]=结果[j+1];
结果[j+1]=互换;
}
}
}
为了将每个数字与整个阵列进行比较,您需要有2个循环
气泡排序示例
public static void bubbleSort(int[] numArray) {
int n = numArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numArray[j - 1] > numArray[j]) {
temp = numArray[j - 1];
numArray[j - 1] = numArray[j];
numArray[j] = temp;
}
}
}
}
publicstaticvoidbubblesort(int[]numArray){
int n=numaray.length;
内部温度=0;
对于(int i=0;i努马拉[j]){
温度=努马拉伊[j-1];
努马拉伊[j-1]=努马拉伊[j];
努马拉伊[j]=温度;
}
}
}
}
参考这个问题
可以使用一个循环完成(尽管这不是表示冒泡排序的常用方法):
publicstaticvoidmain(字符串参数[]){
int[]tab={9,8,7,6,5,4,3,2};
int i=1;//让我们再次执行冒泡排序
而(i //循环不变量:t[0]问题在于for循环中的i=0
和i++
组合。无论何时进入i=0
分支,都会因为i++
而在1
处重新启动。这会导致在第一次迭代后总是跳过8
,其中9
移动到末尾
因此,要么在-1
处重新启动,要么在else块中使用while循环并仅递增。例如:
int i = 0;
while (i < result.length - 1) {
if (result[i] > result[i+1]) {
permute(result, i)
i = 0;
} else {
i++;
}
}
inti=0;
而(i结果[i+1]){
排列(结果,i)
i=0;
}否则{
i++;
}
}
但是,我建议不要使用单循环冒泡排序,因为算法的复杂性更难看出(它仍然是O(n^2)
,但是只有一个循环,它会给人一种O(n)
的印象).未使用数组选项卡。选项卡数组只是供我与输出中的结果进行比较。不,不是作业。这里的想法是从头开始重新扫描数组(循环中的i=0语句)只要一个置换完成。所以一个循环就足够了。我很确定你需要两个循环来完成这个工作并嵌套它们。记住冒泡排序是O(n^2)
它可以用一个循环完成,但是这个循环的控制变量是向前和向后的,而不是在一个时间间隔内更常见的循环。仍然在O(n²)中这是一个最差的和平均的情况。这并没有真正地回答这个问题。使用的算法有点不同:在循环的中间看到<代码> i=0 < /Cord>。从我的理解,我不认为OP需要一个循环解决方案——他们只想看看冒泡排序算法是如何工作的以及为什么他们的代码。(使用if语句和no second for循环)是错误的。
int i = 0;
while (i < result.length - 1) {
if (result[i] > result[i+1]) {
permute(result, i)
i = 0;
} else {
i++;
}
}