今天陪同事面试,同事问到了单循环冒泡排序,考住了!自己回来试了一下,代码如下所示:
public static void main(String[] args) {
int [] stars = {10,2,21,9,7,6,12,8,1,98,27,32,11,14,11};
int temp = 0;
int lengths = stars.length-1;
for(int j=0 ; j<lengths ; j++){
if(stars[j] > stars[j + 1]){
temp = stars[j];
stars[j] = stars[j+1];
stars[j+1] = temp;
}
if(j == lengths - 1){
lengths = lengths - 1;
j = -1;
}
}
for(int a = 0 ; a < stars.length ; a++)
System.out.print( stars[a] + ",");
}
}
本文分享了一次面试经历中遇到的单循环冒泡排序问题,并提供了具体的Java实现代码示例,通过逐步调整循环边界来优化排序过程。
576

被折叠的 条评论
为什么被折叠?



