University stuff.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MinOppgave3.java 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //Oppgavetekst: implementer en sorteringsalgoritme
  2. import java.util.ArrayList;
  3. import java.util.Scanner;
  4. class MinOppgave3 {
  5. private static void swap(int[] arr, int i1, int i2) {
  6. int tmp = arr[i1];
  7. arr[i1] = arr[i2];
  8. arr[i2] = tmp;
  9. }
  10. //Insertion sort
  11. private static void sort(int[] arr) {
  12. //Iterate through the array, skipping the first value
  13. for (int i = 1; i < arr.length; ++i) {
  14. //Iterate backwards, from the current index,
  15. //until we reach sorted values
  16. int j = i;
  17. while (j > 0 && arr[j-1] > arr[j]) {
  18. //Since the while loop hasn't exited,
  19. //we know arr[j] and arr[j-1] is in the wrong order,
  20. //so we swap them
  21. swap(arr, j, j-1);
  22. j -= 1;
  23. }
  24. }
  25. }
  26. public static void main(String[] args) {
  27. if (args.length == 0) {
  28. System.out.println("Usage: MinOppgave3 <ints>");
  29. System.exit(1);
  30. }
  31. int[] ints = new int[args.length];
  32. //Build array of ints
  33. for (int i = 0; i < args.length; ++i) {
  34. ints[i] = Integer.parseInt(args[i]);
  35. }
  36. //Sort the array; arrays are passed by pointer, so sort()
  37. //modifies the array itself
  38. sort(ints);
  39. //Print the elements in the sorted array
  40. for (int i = 0; i < ints.length; ++i) {
  41. System.out.print(ints[i]);
  42. if (i != ints.length - 1) {
  43. System.out.print(", ");
  44. }
  45. }
  46. System.out.println("");
  47. }
  48. }