TORONTO KIDS COMPUTER CLUB | Aurora Thursday Java 18:00 – 05.13
19462
post-template-default,single,single-post,postid-19462,single-format-standard,ajax_fade,page_not_loaded,,no_animation_on_touch,qode-theme-ver-7.6.2,wpb-js-composer js-comp-ver-6.10.0,vc_responsive

Aurora Thursday Java 18:00 – 05.13

18 May Aurora Thursday Java 18:00 – 05.13

Question:

Given an array as below

[6,7,1,3,4,2,9,5]

Sort the above array using selection Sort.

The steps of the selection sort are as below:

arr[] = 64 25 12 22 11

// Find the maximum element in arr[0…4]
// and place it at end of arr[0…4]
11 25 12 22 64

// Find the maximum element in arr[0…3]
// and place it at end of arr[0…3]
11 22 12 25 64

// Find the maximum element in arr[0…2]
// and place it at end of arr[0…2]
11 12 22 25 64

// Find the maximum element in arr[0…1]
// and place it at end of arr[0…1]
11 12 22 25 64

Below is the starter function you can use

     /*
     * Use the below function as the starting example
     * The below function, takes the largest number in the
     * array and puts the number at the end
     */
    public static void selectionSort(int[] arr) {

          int max = arr[0];
          int max_index = 0;
          for(int i = 0; i < arr.length; i++) {
              if(arr[i] > max) {
                   max = arr[i];
                   max_index = i;
              }
          }

          //swap item at max_index with item at arr.length - 1
          int temp = arr[max_index];
          arr[max_index] = arr[arr.length - 1];
          arr[arr.length - 1] = temp;
          // do this step
    }
No Comments

Sorry, the comment form is closed at this time.