SelectionSort

# SelectionSort - in each pass. At the end of each pass it...

This preview shows page 1. Sign up to view the full content.

Simple selection sort The basic idea is to look at each element in the array, and for each element look at all remaining elements to see if there is something smaller that should be in this position. If there is, exchange the two values. 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; } } } } More efficient selection sort - Move every value only once This more efficient variation of selection sort remembers the index of the smallest element that it finds
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: in each pass. At the end of each pass it makes one exchange, if necessary. This is more efficient, but you shouldn't be writing your own sort - use java.util.Arrays.sort(. ..) ! public static void selectionSort2(int x) { for (int i=0; i<x.length-1; i++) { int minIndex = i; // Index of smallest remaining value. for (int j=i+1; j<x.length; j++) { if (x[minIndex] > x[j]) { minIndex = j; // Remember index of new minimum } } if (minIndex != i) { //. .. Exchange current element with smallest remaining. int temp = x[i]; x[i] = x[minIndex]; x[minIndex] = temp; } } }...
View Full Document

## This document was uploaded on 09/21/2009.

Ask a homework question - tutors are online