Advertisement
Stefi16524

SELECTION

May 2nd, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1.  
  2. public class SelectionSort {
  3.  
  4.  
  5. void sort(int arr[]) {
  6.  
  7. int n = arr.length;
  8.  
  9. // One by one move boundary of unsorted subarray
  10. for (int i = 0; i < n-1; i++)
  11. {
  12. // Find the minimum element in unsorted array
  13. int min_idx = i;
  14. for (int j = i+1; j < n; j++)
  15. if (arr[j] < arr[min_idx])
  16. min_idx = j;
  17.  
  18. // Swap the found minimum element with the first
  19. // element
  20. int temp = arr[min_idx];
  21. arr[min_idx] = arr[i];
  22. arr[i] = temp;
  23. }
  24. }
  25.  
  26. // Prints the array
  27. void printArray(int arr[])
  28. {
  29. int n = arr.length;
  30. for (int i=0; i<n; ++i)
  31. System.out.print(arr[i]+" ");
  32. System.out.println();
  33. }
  34.  
  35. // Driver code to test above
  36. public static void main(String args[])
  37. {
  38. SelectionSort ob = new SelectionSort();
  39. int arr[] = {12,2,45,4,39,74};
  40. ob.sort(arr);
  41. System.out.println("Sorted array");
  42. ob.printArray(arr);
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement