0

Algorithm Error, What's Wrong ?

I have this algorithm meant to sort (manually, no Java function) an array with user input elements. But when I run it, i always get some kind of error. What is wrong ? import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int aux,i; int[] V=new int[101]; int n=scan.nextInt(); for(i=0;i<=n;i++) V[i]=scan.nextInt(); for(i=0;i<=n;i++){ aux=V[i]; if(V[i]>V[i+1]){ V[i]=V[i+1]; V[i+1]=aux; } } for(i=0;i<=n;i++) System.out.println(V[i]); } }

17th Jan 2017, 9:53 PM
Razvan Berbece
Razvan Berbece - avatar
3 Answers
0
this isn't correct you are trying to sort in o(n) best sort algorithms are o(nlog) this array is counter example: [3 , 2 , 1]
17th Jan 2017, 10:56 PM
kerpoo
kerpoo - avatar
0
Kerpoo, can you be more explicite please ?
18th Jan 2017, 5:53 AM
Razvan Berbece
Razvan Berbece - avatar
0
it has proved u never can sort an array of n element in o(n) computation and the best is o(nlogn) , in above u are trying to sort in 3n computation! let the minimum element is in the end of array and after sort must be at first, so with above code never can!
18th Jan 2017, 7:25 AM
kerpoo
kerpoo - avatar