1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Iterating through an array

  1. Sep 1, 2011 #1
    I'm trying to understand a sorting algorithm (selection sort, to be exact). I started out with this:

    public static void selectionSort1(int[] x) {
    for (int i=0; i<x.length-1; i++) {
    for (int j=1; j<x.length; j++) {
    if (x > x[j]) {
    //... Exchange elements
    int temp = x;
    x = x[j];
    x[j] = temp;
    }
    }
    }
    }

    but that didn't work so i made one slight modification by changing j to i + 1

    public static void selectionSort1(int[] x) {
    for (int i=0; i<x.length-1; i++) {
    for (int j=i+1; j<x.length; j++) {
    if (x > x[j]) {
    //... Exchange elements
    int temp = x;
    x = x[j];
    x[j] = temp;
    }
    }
    }
    }

    i'm having trouble figuring out what's the difference between the codes?
     
  2. jcsd
  3. Sep 1, 2011 #2
    The first one will not work because you check:
    first iteration:
    x[0] > x[1]
    x[0] > x[2]
    x[0] > x[3]
    and so on. This will work for first iteration.
    some iterations later:
    x[3] > x[1]
    x[3] > x[2]
    x[3] > x[3]
    and so on. This will not work because now you will switch places with numbers already sorted.
    For example x[3] will for sure be larger than x[1] because x[1] is sorted to be the second smallest number. And when they switch a larger number is placed in x[1].

    Second code works because
    first iteration:
    x[0] > x[1]
    x[0] > x[2]
    x[0] > x[3]
    and so on
    some iterations later:
    x[3] > x[4]
    x[3] > x[5]
    x[3] > x[6]
    this will work because you discard the already checked values which is not the case in the first code
     
    Last edited: Sep 1, 2011
  4. Sep 1, 2011 #3

    Mark44

    Staff: Mentor

    When you include code in your post, please put (code) and (/code) tags around it (with the tags in brackets [] though). Doing this preserves your formatting and makes your code easier to read.

    I have edited your post to do this.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Iterating through an array
  1. Array C++ (Replies: 2)

  2. C - array (Replies: 2)

  3. Function and array (Replies: 26)

  4. Iterative Circuit (Replies: 14)

Loading...