Skip to content
Snippets Groups Projects
Commit b664ff62 authored by Radu-Andrei Coanda's avatar Radu-Andrei Coanda
Browse files

init

parents
No related branches found
No related tags found
No related merge requests found
public class List {
public static final List EMPTY = new List(null, 0);
private int value;
private List next;
public List(List n, int v) {
this.next = n;
this.value = v;
}
public List getNext() {
return this.next;
}
public int getValue() {
return this.value;
}
// Teil b
public int length() {
if(this.next == List.EMPTY) {
return 1;
}
return 1 + this.next.length();
}
public String toString() {
if(this.next == List.EMPTY) {
return this.value + ";";
}
return this.value + ", " + this.next.toString();
}
// Teil c
public List getSublist(int i) {
if(i == 0) {
return this.EMPTY;
}
return new List(this.next.getSublist(i-1), this.value);
}
}
\ No newline at end of file
public class ListExercise {
public static List mergesort(List list) {
if(list.length() <= 1) {
return list;
}
List[] divisonList = ListExercise.divide(list);
return merge(mergesort(divisonList[0]), mergesort(divisonList[1]));
}
public static List merge(List first, List second) {
if(first == List.EMPTY) {
return second;
}
if(second == List.EMPTY) {
return first;
}
if(first.getValue() < second.getValue()) {
return new List(ListExercise.merge(first.getNext(), second), first.getValue());
} else {
return new List(ListExercise.merge(first, second.getNext() ), second.getValue());
}
}
/**
* Divides a list of at least two elements into two lists of the same
* length (up to rounding).
*/
private static List[] divide(List list) {
List[] res = new List[2];
int length = list.length() / 2;
res[0] = list.getSublist(length);
for (int i = 0; i < length; i++) {
list = list.getNext();
}
res[1] = list;
return res;
}
/**
* Creates a list from the given inputs and outputs the sorted list and
* the original list thereafter.
*/
public static void main(String[] args) {
if (args != null && args.length > 0) {
List list = buildList(0,args);
System.out.println(mergesort(list));
System.out.println(list);
}
}
/**
* Builds a list from the given input array.
*/
private static List buildList(int i, String[] args) {
if (i < args.length) {
return new List(buildList(i + 1,args), Integer.parseInt(args[i]));
} else {
return List.EMPTY;
}
}
}
public class Main {
public static void main(String[] args) {
List myList = new List(List.EMPTY, 5);
List myList2 = new List(myList, 4);
List myList3 = new List(List.EMPTY, 1);
List myList4 = new List(myList3, 0);
System.out.println(myList2.length());
System.out.println(myList2);
System.out.println(myList2.getSublist(1).toString());
List mergeList = ListExercise.merge(myList2, myList4);
System.out.println(mergeList);
}
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment