# Iterating through an array

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?

The first one will not work because you check:
first iteration:
x > x
x > x
x > x
and so on. This will work for first iteration.
some iterations later:
x > x
x > x
x > x
and so on. This will not work because now you will switch places with numbers already sorted.
For example x will for sure be larger than x because x is sorted to be the second smallest number. And when they switch a larger number is placed in x.

Second code works because
first iteration:
x > x
x > x
x > x
and so on
some iterations later:
x > x
x > x
x > x
this will work because you discard the already checked values which is not the case in the first code

Last edited:
Mark44
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.
I'm trying to understand a sorting algorithm (selection sort, to be exact). I started out with this:
Code:
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[i] > x[j]) {
//... Exchange elements
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
}
but that didn't work so i made one slight modification by changing j to i + 1
Code:
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[i] > x[j]) {
//... Exchange elements
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
}
i'm having trouble figuring out what's the difference between the codes?