Advertisement
LoganBlackisle

selectionsort

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