Java:

public class SelectionSort {
  private List<Integer> nos;
  
  public SelectionSort(List<Integer> nos) {
	this.nos = nos;
  }
  
  public void sort() {
	if (this.nos == null || this.nos.size() == 0 || this.nos.size() == 1) {
	  return;
	}
	
	int count = 0;
	
	while (count < this.nos.size() - 1) {
	  int smallest = this.nos.get(count);
	  int smallestIdx = count;
	  for (int i = count; i < this.nos.size(); ++i) {
		if (this.nos.get(i) < smallest) {
		  smallest = this.nos.get(i); 
		  smallestIdx = i;
		}
	  }
	  
	  swap(count, smallestIdx);
	  ++count;
	}
  }
  
  protected void swap(int firstIdx, int secondIdx) {
	int temp = this.nos.get(secondIdx);
	this.nos.set(secondIdx, this.nos.get(firstIdx));
	this.nos.set(firstIdx, temp);
  }
  
  public static void main(String[] args) {
	List<Integer> nos = new ArrayList<Integer>(Arrays.asList(new Integer[] {3, 6, 1, 5, 4, 2}));
	SelectionSort selectionSort = new SelectionSort(nos);
	selectionSort.sort();
	
	System.out.println(nos);
  }

}

Python:

nos = [3, 6, 1, 5, 4, 2]

count = 0;
while count < len(nos) - 1 :
	smallest = nos[count]		
	smallest_idx = count

	for x in range(count, len(nos)) :
		if nos[x] < smallest :
			smallest = nos[x]
			smallest_idx = nos.index(smallest)
		
	nos[count], nos[smallest_idx] = nos[smallest_idx], nos[count]
	count = count + 1

print nos
Advertisements