Advertisement
Guest User

Untitled

a guest
Dec 16th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1.  
  2. public class SelectionSortHomeWork {
  3.  
  4. public static void main(String[] args) {
  5.  
  6. int[] array = {5, 3, 9, 7, 4, 1};
  7. selectionSort(array);
  8. printArray(array);
  9.  
  10.  
  11. }
  12. static void printArray(int[] arr) {
  13. for (int i = 0; i < arr.length; i++) {
  14. System.out.print(arr[i] + " ");
  15. }
  16. }
  17.  
  18. static void selectionSort(int[] arr) {
  19.  
  20. for (int x = 0; x < arr.length/2; x++) {
  21. int min = arr[x];
  22. int minIndex = x;
  23. int max = arr[x];
  24. int maxIndex = x;
  25.  
  26. for( int i = x + 1; i < arr.length-1-x; i++) {
  27. if(arr[i] < min) {
  28. min = arr[i];
  29. minIndex = i;
  30. }
  31. if(arr[i] > max) {
  32. max = arr[i];
  33. maxIndex = i;
  34. }
  35. }
  36. int temp = arr[x];
  37. arr[x] = arr[minIndex];
  38. arr[minIndex] = temp;
  39.  
  40. if(minIndex == arr.length-1) {
  41. minIndex = maxIndex;
  42. }
  43.  
  44. temp = arr[x];
  45. arr[x] = arr[maxIndex];
  46. arr[maxIndex] = temp;
  47. }
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement