import java.util.Scanner; class SortLispLists8 { public static void main(String[] args) { Scanner in = new Scanner(System.in); LispList ls; System.out.print("Enter a list (of integers): "); String str = in.nextLine(); ls = parseIntLispList(str); System.out.print("The list you entered is: "); System.out.println(ls); System.out.print("The list sorted is: "); System.out.println(sort(ls)); } public static LispList sort(LispList ls) // Returns a list containing the elements of ls in numerical ascending order. // Sorts using merge sort with iterative merge. { if(ls.isEmpty()||ls.tail().isEmpty()) return ls; LispList ls1 = LispList.empty(); LispList ls2 = LispList.empty(); for(;!ls.isEmpty(); ls=ls.tail()) { ls1 = ls1.cons(ls.head()); ls = ls.tail(); if(!ls.isEmpty()) ls2 = ls2.cons(ls.head()); else break; } ls1 = sort(ls1); ls2 = sort(ls2); return merge(ls1,ls2); } public static LispList merge(LispList ls1,LispList ls2) { LispList ls3 = LispList.empty(); while(!ls1.isEmpty()&&!ls2.isEmpty()) { Integer h1 = ls1.head(); Integer h2 = ls2.head(); if(h1.compareTo(h2)<0) { ls3 = ls3.cons(h1); ls1 = ls1.tail(); } else { ls3 = ls3.cons(h2); ls2 = ls2.tail(); } } if(!ls2.isEmpty()) ls1=ls2; while(!ls3.isEmpty()) { Integer h = ls3.head(); ls1 = ls1.cons(h); ls3 = ls3.tail(); } return ls1; } public static LispList parseIntLispList(String str) { String line = str.trim(); String contents = line.substring(1,line.length()-1).trim(); if(contents.length()==0) return LispList.empty(); String[] nums = contents.split(","); LispList list = LispList.empty(); for(int i=nums.length-1; i>=0; i--) { String num = nums[i].trim(); list = list.cons(Integer.parseInt(num)); } return list; } }