【发布时间】:2015-12-27 09:20:38
【问题描述】:
Chandu 的女朋友喜欢按非升序排序的数组。今天是她的生日。 Chandu 想在她生日那天给她一些排序好的数组。但是商店只有未排序的数组。所以,Chandu 买了 T 个未排序的数组,并试图对它们进行排序。但是,由于生日聚会迟到了,他没有太多时间手动对数组进行排序。所以,他要求你编写一个程序,以非递增顺序对 T 数组进行排序。帮助他,否则他的女朋友会杀了他。
输入:
第一行包含一个整数 T,表示测试用例的数量。 每个测试用例的第一行包含一个整数 N,表示数组的大小。 第二行包含 N 个空格分隔的整数,表示数组元素 Ai。
输出:
对于每个测试用例,以非递增顺序打印排序后的数组。
约束:
1 <= T <= 100
1 <= N <= 105
0 <= Ai <= 109
我的方法
我的第一种方法是使用简单的方法对解决方案进行编码。为此,我尝试了冒泡排序算法。但在最后一个测试用例中,我没有得到预期的输出。我使用冒泡排序对元素进行排序,比较每个元素的相邻元素排序循环中k的迭代。因此,最小的元素将在最后
谁能指导我为什么?
下面是代码:
public static void main(String args[] ) throws Exception
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();//Take the int Input from user
sc.nextLine(); //to move to nextLine after consuming token
int NoOfElements=sc.nextInt();
sc.nextLine();//to move to nextLine
int x[]=new int[NoOfElements];
for(int i=1;i<=T;i++)
{
for(int j=0;j<NoOfElements;j++)
{
x[j]=sc.nextInt();
}
sort(x);
}
}
public static void sort(int p[])
{
for(int k=0;k<p.length-1;k++)
{
//bubble sort
for(int i=0;i<p.length-k-1;i++)
{
if(p[i]<p[i+1])
{
//swap
int temp=p[i];
p[i]=p[i+1];
p[i+1]=temp;
}
}
}
for(int m=0;m<p.length;m++)
{
System.out.print(p[m]);
System.out.print(" ");
}
System.out.println();
}
}
Input
2
5
2 5 2 4 3
5
5 4 2 3 1
My Code's Output
5 4 3 2 2
5 5 4 3 2 //Why I am getting 5 here.I could not correct it.
Expected Correct Output
5 4 3 2 2
5 4 3 2 1
【问题讨论】: