Skip to content

Instantly share code, notes, and snippets.

@xynophon
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save xynophon/fef8044a53b28c9eaf13 to your computer and use it in GitHub Desktop.

Select an option

Save xynophon/fef8044a53b28c9eaf13 to your computer and use it in GitHub Desktop.
/**
* Created by xynophon on 15.1.13.
*/
import java.util.Random;
public class sort {
public double[] swap(double[] arr, int i, int j){
double temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
public double[] selection_sort(double[] arr) {
for (int i = 0; i < arr.length; i++) {
int min_item = i;
for (int j = min_item + 1; j < arr.length; j++) {
if (arr[min_item] > arr[j])
min_item = j;
}
swap(arr, i, min_item);
}
return arr;
}
public double[] insertion_sort(double[] arr){
for(int i = 0; i < arr.length; i++){
int index = i;
while(index > 0 && arr[index] < arr[index-1]){
swap(arr, index, index-1);
index--;
}
}
return arr;
}
public static void main(String args[]){
sort sr = new sort();
Random rnd = new Random();
double[] numbers = new double[15];
for(int i = 0; i < 15; i++)
numbers[i] = rnd.nextDouble()*10;
double[] arr_sel = sr.selection_sort(numbers);
System.out.println("selection : ");
for(double number : arr_sel)
System.out.print(number + " ");
System.out.println();
double[] arr_ins = sr.insertion_sort(numbers);
System.out.println("insertion : ");
for(double number : arr_ins)
System.out.print(number + " ");
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment