/* MergeSort.java
CSC 225 - Spring 2016
Assignment 2 - Template for Merge Sort (Linked List version)
This template includes some testing code to help verify the implementation.
To interactively provide test inputs, run the program with
java MergeSort
To conveniently test the algorithm with a large input, create a
text file containing space-separated integer values and run the program with
java MergeSort file.txt
where file.txt is replaced by the name of the text file.
NOTE: For large input files, the depth of recursion may cause the Java
runtime environment to run out of stack space. To remedy this, run java
with the extra parameter "-Xss64m" (which increases the stack size to 64
megabytes). For example: java -Xss64m MergeSort input_data.txt
B. Bird & M. Simpson - 03/22/2015
*/
import java.util.Scanner;
import java.util.Vector;
import java.util.Arrays;
import java.io.File;
//Do not change the name of the MergeSort class
public class MergeSort{
/* MergeSort(head)
Given a reference to the head of a list, sort the contents of the list
with merge sort and return a reference to the sorted list. Your
implementation may create a new list or modify the input list.
To achieve full marks, you may not use any iterative loop constructs
(including for loops, while loops or do-while loops); all iteration
must be accomplished with recursion.
You may add additional functions (or classes) if needed, but the entire program must be
contained in this file.
Do not change the function signature (name/parameters).
*/
public static ListNode MergeSort(ListNode head){
/* ... Your code here ... */
return head;
}
/* ListNode class */
/* Do not change, add or remove any aspect of the class definition below.
If any of the contents of this class are changed, your submission will
not be marked.
The members of the class should be accessed directly (e.g. node.next,
node.value), since no get/set methods exist.
However, you may create a subclass of this class if you want to extend
its functionality. Ensure that your subclass is contained in MergeSort.java
with the rest of your code (since you may only submit one file).
*/
public static class ListNode{
int value;
ListNode next;
public ListNode(int value){
this.value = value;
this.next = null;
}
public ListNode(int value, ListNode next){
this.value = value;
this.next = next;
}
}
/* Testing code */
/* listLength(node)
Compute the length of the list starting at the provided node.
*/
public static int listLength(ListNode node){
if (node == null)
return 0;
return 1 + listLength(node.next);
}
/* testSorted(node)
Returns true if all elements of the list starting at the provided node
are in ascending order.
*/
public static boolean testSorted(ListNode node){
//An empty list is always considered sorted.
if (node == null)
return true;
//A list with one element is always considered sorted.
if (node.next == null)
return true;
//Test whether the first element is greater than the second element
if (node.value > node.next.value){
//If so, the list is not sorted.
return false;
}else{
//Otherwise, test whether the remaining elements are sorted and
//return the result.
return testSorted(node.next);
}
}
/* printList(node)
Print all list elements starting at the provided node.
*/
public static void printList(ListNode node){
if (node == null)
System.out.println();
else{
System.out.print(node.value + " ");
printList(node.next);
}
}
/* readInput(inputScanner)
Read integer values from the provided scanner into a linked list.
Each recursive call reads one value, and recursion ends when the user
enters a negative value or the input file ends.
*/
public static ListNode readInput(Scanner inputScanner){
//If no input is left, return an empty list (i.e. null)
if (!inputScanner.hasNextInt())
return null;
int v = inputScanner.nextInt();
//If the user entered a negative value, return an empty list.
if (v < 0)
return null;
//If the user entered a valid input value, create a list node for it.
ListNode node = new ListNode(v);
//Scan for more values recursively, and set the returned list of values
//to follow the node we just created.
node.next = readInput(inputScanner);
//Return the created list.
return node;
}
/* main()
Contains code to test the MergeSort function. Nothing in this function
will be marked. You are free to change the provided code to test your
implementation, but only the contents of the MergeSort() function above
will be considered during marking.
*/
public static void main(String[] args){
Scanner s;
if (args.length > 0){
try{
s = new Scanner(new File(args[0]));
} catch(java.io.FileNotFoundException e){
System.out.printf("Unable to open %s\n",args[0]);
return;
}
System.out.printf("Reading input values from %s.\n",args[0]);
}else{
s = new Scanner(System.in);
System.out.printf("Enter a list of non-negative integers. Enter a negative value to end the list.\n");
}
ListNode inputListHead = readInput(s);
int inputLength = listLength(inputListHead);
System.out.printf("Read %d values.\n",inputLength);
long startTime = System.currentTimeMillis();
ListNode sortedListHead = MergeSort(inputListHead);
long endTime = System.currentTimeMillis();
double totalTimeSeconds = (endTime-startTime)/1000.0;
//Compute the length of the output list
int sortedListLength = listLength(sortedListHead);
//Don't print out the values if there are more than 100 of them
if (sortedListLength <= 100){
System.out.println("Sorted values:");
printList(sortedListHead);
}
//Check whether the sort was successful
boolean isSorted = testSorted(sortedListHead);
System.out.printf("List %s sorted.\n",isSorted? "is":"is not");
System.out.printf("Total Time (seconds): %.2f\n",totalTimeSeconds);
}
}
- 大小: 518.4 KB
- 大小: 169.5 KB
分享到:
相关推荐
非递归归并排序.cpp
### 递归归并排序算法 #### 一、概述 归并排序是一种高效的排序算法,其核心思想是分而治之。它通过递归地将数组分成两半,然后对每一半进行排序,并最终合并两个有序数组来实现整体排序。由于归并排序采用的是...
在C++中实现非递归归并排序,主要涉及以下几个步骤: 1. **分割数组**:首先,我们需要将原始数组分割成两个部分。这通常通过一个中间索引完成,将数组分为两半。例如,如果我们有一个大小为n的数组,我们可以选择...
三、实现非递归归并排序的步骤 1. 将需要排序的数组分成小数组,并对每个小数组进行排序。 2. 使用迭代的方式将已排序的小数组合并成一个大的已排序数组。 3. 使用临时数组来存储中间结果,以避免对原始数组的修改...
非递归归并排序详细分析,Java实现. 非常详细,基本上可以看明白
这里有三个主要的排序算法:归并排序、消除递归的归并排序和快速排序,它们都是在Java编程语言中实现的。让我们深入探讨这些算法及其Java实现。 1. **归并排序(Merge Sort)** 归并排序是一种基于分治思想的排序...
接下来,我们深入分析给出的部分代码,以理解非递归归并排序的具体实现细节: 首先,代码包含了标准输入输出流库`#include<iostream>`,并使用了`using namespace std;`简化后续代码中的命名空间引用。定义了两个...
在本篇《Java数据结构和算法》学习笔记中,我们将深入探讨递归和归并排序。递归是一种强大的编程技术,常用于解决复杂问题,而归并排序则是利用递归实现的一种高效排序算法。 首先,让我们理解什么是递归。递归是...
c++实现的合并排序算法 用递归和非递归两种方式实现的
2. **非递归实现**:非递归归并排序使用循环和栈来模拟递归的过程。它通过维护一个栈来保存待合并的子序列,每次从栈中取出两个子序列进行合并,然后将新产生的子序列压入栈中,直至栈为空,整个序列排序完成。这种...
以下是关于"插入排序、选择排序、希尔排序、堆排序、冒泡、双向冒泡、快速排序、归并排序、递归的归并排序、基数排序"这十大经典排序算法的详细解释: 1. 插入排序:插入排序是一种简单的排序算法,它通过构建有序...
合并排序的C程序。递归写法。第一次上传文件。谢谢大家支持。
- `mergeSort`函数实现了递归归并排序的核心逻辑。 - 首先检查是否满足递归终止条件,即`left >= right`。 - 计算中间位置`mid`,将数组分成左右两部分,然后递归调用`mergeSort`分别对两部分排序。 - 调用`...
二分归并排序通常使用递归实现,MATLAB中的实现可能涉及两个辅助函数,一个用于分割数组,另一个用于合并已排序的子数组。这种算法在处理大数据集时效率高,时间复杂度为O(n log n)。 3. **归并排序**(Merge Sort...
递归实现的二路归并排序算法,其中对结构体按其内部一个关键字(本例是对一个任务结构体,按其收益排序)进行排序
总的来说,非递归归并排序的关键在于设计合适的循环结构来模拟递归调用,并实现有效的合并操作。在实际编程中,为了提高效率,通常还会考虑使用指针来优化内存访问,以及考虑边界条件来避免不必要的操作。
该方法实现了递归归并排序的核心逻辑。 ```java public static void mergeSort(int[] a, int s, int len) { int size = a.length; int mid = size / (len ); int c = size & ((len ) - 1); if (mid == 0) ...
// 主函数,调用递归归并排序 void recursive_merge_sort(Node*& sub_list, int len); // 递归归并排序函数 Node* divide_from(Node* sub_list, int len); // 分割函数 Node* merge(Node* first, Node* second);...
1. **递归归并排序**: 递归归并排序是归并排序最直观的实现方式。它首先将数组分成两半,分别对这两半进行排序,然后将已排序的两个子数组合并成一个有序数组。这个过程会一直递归下去,直到子数组只剩下一个元素...
2. **递归**:归并排序的分治过程通常用递归来实现。在C语言中,递归函数可以方便地处理这种自相似的问题。递归调用需要一个基本情况(base case),即当数组只有一个或零个元素时,可以直接认为它是有序的,无需再...