import java.io.*; class SelectionSort { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter name of the source file: "); FileReader fr =new FileReader(br.readLine()); char[] buffer = new char[2048]; int len = fr.read(buffer); String data = new String(buffer,0,len); String[] element = data.split(","); int[] a = new int[element.length]; System.out.println("\n\nBefore Sorting: "); for(int i=0; i<a.length; i++) { a[i] = Integer.parseInt(element[i]); System.out.print(a[i]+"\t"); } int c=0,m=0; //variables to keep track of comparisons and moves //Main logic of selection sort for(int i=0; i<a.length-1; i++) { int min=i; for(int j=i+1; j<a.length; j++) { c++; if(a[min]>a[j]) min=j; } if(min!=i) { int temp = a[min]; a[min] = a[i]; a[i] = temp; m+=3; } } System.out.println("\n\nAfter Sorting: "); for(int i=0; i<a.length; i++) { System.out.print(a[i]+"\t"); } System.out.println("\n\nComparisons = " + c + "\tMoves = " + m); } catch (Exception e) { e.printStackTrace(); } } }
No comments:
Post a Comment
Your comments are very much valuable for us. Thanks for giving your precious time.