Chandu的女朋友喜歡按照非遞增順序排序的數組。今天是她的生日。 Chandu想在她的生日時給她一些排序的陣列。但店鋪只有未排序的陣列。所以,Chandu購買了T未排序的數組,並試圖對它們進行排序。但是,他沒有太多時間手動排列陣列,因爲他爲生日派對遲到了。所以,他要求你編寫一個程序,以不增加的順序排列T陣列。幫助他,或者他的女朋友會殺了他。用於排列NonDecreasing Order中的元素的輸出不符合預期?
輸入:
第一行包含一個整數T,表示的測試用例的數量。 每個測試用例的第一行包含一個整數N,表示數組的大小。 第二行包含N個空格分隔的整數,表示數組元素Ai。
輸出:
對於每個測試用例,以非遞增順序打印排序後的數組。
約束:
1 <= T <= 100
1 <= N <= 105
0 <= Ai <= 109
MYApproach
我的第一種方法是使用簡單的approach.For的解決方案代碼這一點,我想冒泡Algorithm.But在過去的測試用例,我沒有得到Expected Output.I使用冒泡排序對在排序循環中每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