黑马程序员技术交流社区
标题:
关于数组排序的问题
[打印本页]
作者:
庄纪光
时间:
2011-9-25 10:48
标题:
关于数组排序的问题
想把数组a[]中的一组数字按从小到大的顺序排列并输出,可是下面的代码运行后得不到想要的结果,请哪位高手给指点一下!先谢谢了。
package test;
/**
*
* @author Administrator
*/
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int a[]={15,7,8,23,34,25};
int temp,i;
for( i=0;i<=a.length-1;i++)
{
for(int j=0;j<a.length-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
System.out.println(a[j]);
}
}
}
}
作者:
刘朋朋
时间:
2011-9-25 11:03
汗,对你无语了,你已经对数组进行了排序,但是你的输出不是地方啊!!!
你可以把你的输出语句删掉,然后用for循环重新对数组输出,就是你要的结果了:
我给你改得代码,你看下:[code=java]public static void main(String[] args) {
int a[] = { 15, 7, 8, 23, 34, 25 };
int temp, i;
for (i = 0; i <= a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
//遍历数组,并输出
for(int n : a){
System.out.println(n);
}
}[/code]
[
本帖最后由 刘朋朋 于 2011-09-25 11:06 编辑
]
作者:
匿名
时间:
2011-9-25 11:44
输出不是地方,有的是错误的:可以参考下面的 :
class demo
{
public static void main(String[] args)
{
int[] arr={7,8,6,9,1,3,5,4};
//在排序前打印;
printarray(arr);
paixun(arr);
printarray(arr);
}
//排序功能函数
public static void paixun(int[] arr)
{
for (int x=0;x<arr.length-1 ;x++ )
{
for (int y=x+1;y<arr.length ;y++ )
{
if(arr[x]>arr[y])
{
int temp=arr[x];
arr[x]=arr[y];
arr[y]=temp;
}
}
}
}
//打印功能函数
public static void printarray(int[] arr)
{
System.out.print("[");
for (int x=0;x<arr.length ;x++ )
{
if(x!=arr.length-1)
System.out.print(arr[x]+", ");
else
System.out.println(arr[x]+"]");
}
}
}
/*
选择排序
排序:从小到大
{7,5,6,9,1,3,5,4}
*/
作者:
匿名
时间:
2011-9-25 17:05
在这个位置打印出来的,是每轮有比较的值。 如果要打印出排序后的数组,参考刘朋朋的代码就是了
作者:
匿名
时间:
2011-9-26 18:46
谢谢你们的解答!
作者:
匿名
时间:
2011-9-26 19:16
呵呵,看你错了吧,双重for循环的功能只是用于排序的,这时你不能在双重for循环中做别的事的。 System.out.println(a[j]);这句话在内层for中,那么每次 执行if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}之后都会执行System.out.println(a[j]);此时你并没有完成排序的情况下就输出了数组中的元素,这就 造成了你所看到的结果。下面是我对你写的程序的略微改动,实现了你的愿望,你自己运行看看吧,嘿嘿。
public class Test {
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int a[] = { 15, 7, 8, 23, 34, 25 };
int temp, i;
for (i = 0; i <= a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
//System.out.println(a[j]);
}
}
for(int n = 0;n <a.length;n++){
System.out.print(a[n]+",");
}
}
}
运行结果:7,8,15,23,25,34,
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2