Hey.
Ja du roder lidt rundt i det. Og så laver du virkelig mange unødvendige variabler...
Jeg har fikset koden for dig:
- import java.util.ArrayList;
-
- public class Merge {
-
- public static void main(String a[]) {
-
- ArrayList<Integer> list = new ArrayList<Integer>();
-
- list.add(123);
- list.add(122);
- list.add(1);
- list.add(2);
- list.add(123212);
- list.add(142);
-
-
- System.out.println("Listen før sortering:");
- System.out.println(list);
-
- ArrayList<Integer> resultList = mergeSort_srt(list, 0, list.size()-1);
- System.out.println("Listen efter sortering:");
- System.out.println(resultList);
- }
-
-
- public static ArrayList<Integer> mergeSort_srt(ArrayList<Integer> list, int low, int high) {
- ArrayList<Integer> resultList = new ArrayList<Integer>();
-
- //Base case
- if (low >= high) {
- resultList.add(list.get(low));
- return resultList;
- }
-
- int middle = (low + high) / 2;
- //Recursive case
- ArrayList<Integer> leftList = mergeSort_srt(list, low, middle);
- ArrayList<Integer> rightList = mergeSort_srt(list, middle + 1, high);
-
- //We check if we shall take from left or right list
- while ((leftList.size() > 0) && (rightList.size() > 0)) {
- if (leftList.get(0) < rightList.get(0)) {
- resultList.add(leftList.get(0));
- leftList.remove(0);
- } else {
- resultList.add(rightList.get(0));
- rightList.remove(0);
- }
- }
- //Now we just empty the list which is not empty
- while(rightList.size() > 0){
- resultList.add(rightList.get(0));
- rightList.remove(0);
- }
- while(leftList.size() > 0){
- resultList.add(leftList.get(0));
- leftList.remove(0);
- }
- //Return the sorted list
- return resultList;
- }
- }
Koden her kan godt gøres lidt flottere, men nu lavede jeg det sådan at koden genkender dig.
Indlæg senest redigeret d. 10.10.2012 13:54 af Bruger #5097