- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的java作业中,我必须计算发生的比较次数,以及选择排序、插入排序、冒泡排序、快速排序和合并排序算法的总执行时间。下面的代码是一个驱动程序,用于测试运行算法的代码,同时计算它们的执行时间和比较。在代码中,我用值初始化了列表并通过它们运行它。我得到的唯一输出是“排序列表...”,这只是第一行。其余部分没有运行,我迷路了。请帮忙。
public class SortingTest {
//create 3 constant values
static final int SIZE = 1000;//number of values in the lists
static final int SORTED_ORDER = 0;//for sorted lists
static final int RANDOM_ORDER = 1;//for unsorted lists
//create the lists for each sorting algorithm
static Integer[] selArr = new Integer[SIZE];
static Integer[] insArr = new Integer[SIZE];
static Integer[] bubArr = new Integer[SIZE];
static Integer[] quiArr = new Integer[SIZE];
static Integer[] merArr = new Integer[SIZE];
public static void main(String[] args) {
//perform the sorting on sorted lists
performSorting(SORTED_ORDER);
//perform the sorting on unsorted lists
performSorting(RANDOM_ORDER);
//perform the sorting on unsorted lists
performSorting(RANDOM_ORDER);
}
private static void performSorting(int order) {
if(order == SORTED_ORDER)//display if the lists are in sorted order or not
System.out.println("Sorted Lists...");
else
System.out.println("Unsorted Lists...");
//initialize the lists in sorted order
initLists(order);
//initialize the number of comparisons and total execution time
initComparisonsAndExecutionTime();
//sort the lists
sortLists();
//display the number of comparisons and total execution time
printComparisonsAndExecutionTime();
}
//initializes the lists with the same values
private static void initLists(int order) {
int number;
for(int i=0;i<SIZE;i++) {
if(order == SORTED_ORDER)
number = new Integer(i);
else
number = new Integer((int)(Math.random()*SIZE));
selArr[i] = number;
insArr[i] = number;
bubArr[i] = number;
quiArr[i] = number;
merArr[i] = number;
}
}
/*initializes the number
of comparisons and total execution time for each algorithm*/
private static void initComparisonsAndExecutionTime() {
Sorting.selectionSortComparisons = 0;
Sorting.insertionSortComparisons = 0;
Sorting.bubbleSortComparisons = 0;
Sorting.quickSortComparisons = 0;
Sorting.mergeSortComparisons = 0;
Sorting.selectionSortExecutionTime = 0L;
Sorting.insertionSortExecutionTime = 0L;
Sorting.bubbleSortExecutionTime = 0L;
Sorting.quickSortExecutionTime = 0L;
Sorting.mergeSortExecutionTime = 0L;
}
/*calls each sorting algorithm with the
corresponding lists to sort the values*/
private static void sortLists() {
Sorting.selectionSort(selArr);
Sorting.insertionSort(insArr);
Sorting.bubbleSort(bubArr);
Sorting.quickSort(quiArr);
Sorting.mergeSort(merArr);
}
/*displays the number of comparisons and total execution time
for each algorithm*/
private static void printComparisonsAndExecutionTime() {
System.out.println("----------------------");
System.out.printf("%-15s%15s%15s\n", "SORTING METHOD",
"COMPARISONS", "EXEC.TIME(ns)");
System.out.println("----------------------");
System.out.printf("%-15s%15d%15d\n", "Selection sort",
Sorting.selectionSortComparisons,
Sorting.selectionSortExecutionTime);
System.out.printf("%-15s%15d%15d\n", "Insertion sort",
Sorting.insertionSortComparisons,
Sorting.insertionSortExecutionTime);
System.out.printf("%-15s%15d%15d\n", "Bubble sort",
Sorting.bubbleSortComparisons,
Sorting.bubbleSortExecutionTime);
System.out.printf("%-15s%15d%15d\n", "Quick sort",
Sorting.quickSortComparisons,
Sorting.quickSortExecutionTime);
System.out.printf("%-15s%15d%15d\n", "Merge sort",
Sorting.mergeSortComparisons,
Sorting.mergeSortExecutionTime);
System.out.println("-----------------------\n\n");
}
}
这是所有算法的实现
public class Sorting
{
public static int selectionSortComparisons = 0;
public static int insertionSortComparisons = 0;
public static int bubbleSortComparisons = 0;
public static int quickSortComparisons = 0;
public static int mergeSortComparisons = 0;
public static long selectionSortExecutionTime = 0L;
public static long insertionSortExecutionTime = 0L;
public static long bubbleSortExecutionTime = 0L;
public static long quickSortExecutionTime = 0L;
public static long mergeSortExecutionTime = 0L;
/**
* Sorts the specified array of integers using the selection
* sort algorithm.
*
* @param data the array to be sorted
*/
public static <T extends Comparable<T>>
void selectionSort(T[] data)
{
long startTime = System.nanoTime();//stores the beginning time of
selection sort algorithm
int min;
T temp;
for (int index = 0; index < data.length-1; index++)
{
min = index;
for (int scan = index+1; scan < data.length; scan++) {
selectionSortComparisons++;//counts the number of
comparisons in selection sort
if (data[scan].compareTo(data[min])<0)
min = scan;
}
swap(data, min, index);
}
long endTime = System.nanoTime();//stores the ending time of
selection sort
selectionSortExecutionTime = endTime - startTime;//computes total
execution time of selection sort
}
/**
* Swaps to elements in an array. Used by various sorting algorithms.
*
* @param data the array in which the elements are swapped
* @param index1 the index of the first element to be swapped
* @param index2 the index of the second element to be swapped
*/
private static <T extends Comparable<T>>
void swap(T[] data, int index1, int index2)
{
T temp = data[index1];
data[index1] = data[index2];
data[index2] = temp;
}
/**
* Sorts the specified array of objects using an insertion
* sort algorithm.
*
* @param data the array to be sorted
*/
public static <T extends Comparable<T>>
void insertionSort(T[] data)
{
long startTime = System.nanoTime();//stores beginning time of
insertion sort
for (int index = 1; index < data.length; index++)
{
T key = data[index];
int position = index;
// shift larger values to the right
while (position > 0 && data[position-1].compareTo(key) > 0)
{
insertionSortComparisons++;//counts the number of
comparisons in insertion sort
data[position] = data[position-1];
position--;
}
if (position > 0)
insertionSortComparisons++;//counts the number of comparisons in insertion sort
data[position] = key;
}
long endTime = System.nanoTime();//stores ending time of insertion
sort
selectionSortExecutionTime = endTime - startTime;//computes total execution time of selection sort
}
/**
* Sorts the specified array of objects using a bubble sort
* algorithm.
*
* @param data the array to be sorted
*/
public static <T extends Comparable<T>>
void bubbleSort(T[] data)
{
long startTime = System.nanoTime();//stores the beginning of bubble sort
int position, scan;
T temp;
for (position = data.length - 1; position >= 0; position--)
{
for (scan = 0; scan <= position - 1; scan++)
{
bubbleSortComparisons++;//counts the number of comparisons in bubble sort
if (data[scan].compareTo(data[scan+1]) > 0)
swap(data, scan, scan + 1);
}
}
long endTime = System.nanoTime();//stores end of bubble sort
selectionSortExecutionTime = endTime - startTime;//computes total execution time of bubble sort
}
/**
* Sorts the specified array of objects using the merge sort
* algorithm.
*
* @param data the array to be sorted
*/
public static <T extends Comparable<T>>
void mergeSort(T[] data)
{
long startTime = System.nanoTime();//stores beginning of merge sort
mergeSort(data, 0, data.length - 1);
long endTime = System.nanoTime();//stores end of merge sort
selectionSortExecutionTime = endTime - startTime;//computes total execution time of merge sort
}
/**
* Recursively sorts a range of objects in the specified array using the
* merge sort algorithm.
*
* @param data the array to be sorted
* @param min the index of the first element
* @param max the index of the last element
*/
private static <T extends Comparable<T>>
void mergeSort(T[] data, int min, int max)
{
if (min < max)
{
int mid = (min + max) / 2;
mergeSort(data, min, mid);
mergeSort(data, mid+1, max);
merge(data, min, mid, max);
}
}
/**
* Merges two sorted subarrays of the specified array.
*
* @param data the array to be sorted
* @param first the beginning index of the first subarray
* @param mid the ending index fo the first subarray
* @param last the ending index of the second subarray
*/
@SuppressWarnings("unchecked")
private static <T extends Comparable<T>>
void merge(T[] data, int first, int mid, int last)
{
T[] temp = (T[])(new Comparable[data.length]);
int first1 = first, last1 = mid; // endpoints of first subarray
int first2 = mid+1, last2 = last; // endpoints of second subarray
int index = first1; // next index open in temp array
// Copy smaller item from each subarray into temp until one
// of the subarrays is exhausted
while (first1 <= last1 && first2 <= last2)
{
mergeSortComparisons++;//count the number of comparisons in merge sort
if (data[first1].compareTo(data[first2]) < 0)
{
temp[index] = data[first1];
first1++;
}
else
{
temp[index] = data[first2];
first2++;
}
index++;
}
// Copy remaining elements from first subarray, if any
while (first1 <= last1)
{
temp[index] = data[first1];
first1++;
index++;
}
// Copy remaining elements from second subarray, if any
while (first2 <= last2)
{
temp[index] = data[first2];
first2++;
index++;
}
// Copy merged data into original array
for (index = first; index <= last; index++)
data[index] = temp[index];
}
/**
* Sorts the specified array of objects using the quick sort algorithm.
*
* @param data the array to be sorted
*/
public static <T extends Comparable<T>>
void quickSort(T[] data)
{
long startTime = System.nanoTime();//stores beginning of quick sort
quickSort(data, 0, data.length - 1);
long endTime = System.nanoTime();//stores end of quick sort
selectionSortExecutionTime = endTime - startTime;//computes total execution time of quick sort
}
/**
* Recursively sorts a range of objects in the specified array using the
* quick sort algorithm.
*
* @param data the array to be sorted
* @param min the minimum index in the range to be sorted
* @param max the maximum index in the range to be sorted
*/
private static <T extends Comparable<T>>
void quickSort(T[] data, int min, int max)
{
if (min < max)
{
// create partitions
int indexofpartition = partition(data, min, max);
// sort the left partition (lower values)
quickSort(data, min, indexofpartition - 1);
// sort the right partition (higher values)
quickSort(data, indexofpartition + 1, max);
}
}
/**
* Used by the quick sort algorithm to find the partition.
*
* @param data the array to be sorted
* @param min the minimum index in the range to be sorted
* @param max the maximum index in the range to be sorted
*/
private static <T extends Comparable<T>>
int partition(T[] data, int min, int max)
{
T partitionelement;
int left, right;
int middle = (min + max) / 2;
// use the middle data value as the partition element
partitionelement = data[middle];
// move it out of the way for now
swap(data, middle, min);
left = min;
right = max;
while (left < right)
{
// search for an element that is > the partition element
while (left < right && data[left].compareTo(partitionelement) <= 0)
quickSortComparisons++;//counts the number of comparisons in quick sort
left++;
// search for an element that is < the partition element
while (data[right].compareTo(partitionelement) > 0)
quickSortComparisons++;//counts the number of comparisons in quick sort
right--;
quickSortComparisons++;//counts the number of comparisons in quick sort
// swap the elements
if (left < right)
quickSortComparisons++;//counts the number of comparisons in quick sort
swap(data, left, right);
}
// move the partition element into place
swap(data, min, right);
return right;
}
}
最佳答案
我尝试添加一些打印来帮助调试您的代码。我发现你的快速排序方法陷入了无限循环。
输出是:
Sorted Lists...
Lists Initialized!
Comparisons and Exec time initialized!
Selection done!
Insertion done!
Bubble done!
当我评论这一行时Sorting.quickSort(quiArr);
,我得到以下输出:
----------------------
SORTING METHOD COMPARISONS EXEC.TIME(ns)
----------------------
Selection sort 499500 2726141
Insertion sort 243586 0
Bubble sort 499500 0
Quick sort 0 0
Merge sort 8697 0
-----------------------
这让我检查了您的代码以设置每种排序方法的执行时间。看起来所有方法都设置了 Sorting.selectionSortExecutionTime
,正如您在以下 mergeSort 代码片段中看到的那样:
public static <T extends Comparable<T>> void mergeSort(T[] data) {
long startTime = System.nanoTime();// stores
// beginning
// of
// merge
// sort
mergeSort(data, 0, data.length - 1);
long endTime = System.nanoTime();// stores
// end
// of
// merge
// sort
/* Wrong variable */
selectionSortExecutionTime = endTime - startTime;// computes
// total
// execution
// time
// of
// merge
// sort
}
我在快速排序方法中进行了一些调试,发现如下:while 在 while(left<right)
内循环没有花括号,所以 left++
和right--
省略的地方,只有 quickSortComparisons++
在他们里面。这是固定代码,其中的注释指出了我所描述的内容:
private static <T extends Comparable<T>> int partition(T[] data,
int min,
int max) {
T partitionelement;
int left, right;
int middle = (min + max) / 2;
// use the middle data value as the
// partition element
partitionelement = data[middle];
// move it out of the way for now
swap(data, middle, min);
left = min;
right = max;
while (left < right) {
// search for an element that is >
// the partition element
while (left < right
&& data[left].compareTo(partitionelement) <= 0){
// counts the number of comparisons in quick sort
quickSortComparisons++;
left++; // <--- this was not in the while loop
}
quickSortComparisons++; // <--- I believe you should have this one too
// search for an element that is <
// the partition element
while (data[right].compareTo(partitionelement) > 0){
// counts the number of comparisons in quick sort
quickSortComparisons++;
right--; // <--- this wasn't in the while loop neither
}
// counts the number of comparisons in quick sort
quickSortComparisons++;
// swap the elements
if (left < right)
quickSortComparisons++;// counts the number of comparisons in quick sort
swap(data, left, right);
}
// move the partition element into place
swap(data, min, right);
return right;
}
希望我有帮助!
关于java - 用于计算未正确输出的算法的比较和执行时间的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43827492/
我想使用 NetworkX Graph 对象作为 Python dict 中的键。但是,我不希望默认的比较行为(即通过对象的地址)。相反,我希望同构图是 dict 中相同元素的键。 此行为是否已在某处
这个问题已经有答案了: What is the most effective way for float and double comparison? (33 个回答) 已关闭 7 年前。 在您认为我
我正在学习 C 编程,为了练习,我找到了一个需要解决的任务。这有点像一个游戏,有人选择一个单词,其他人猜测字母。我必须检查有多少给定的单词可能是所选单词的正确答案。 输入: 3 3//数字 n 和 m
我两天前开始学习C,在做作业时遇到了问题。我们的目的是从字符数组中获取字符列表,并通过计算连续字符并将其替换为数字来缩短它。对“a4b5c5”说“aaaabbbbbccccc”。这是我到目前为止的代码
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
为什么我在 if 中的比较不起作用?答案应该是 8 但它返回 0。 function findMissing(missingArray){ var getArray = missing
我想知道为什么以下 JavaScript 比较会给出不同的结果。 (1==true==1) true (2==true==2) false (0==false==0) false (0==false)
我想知道是否有人可以帮助我完成这个程序。编写一个接受两个字符串的函数。该函数应该将这两个字符串与字典顺序上排在第一位的字符串组合起来。两个字符串之间应该有一个空格。在一行上打印结果字符串。在一行上打印
有谁知道一个免费的开源库(实用程序类),它允许您比较一个 Java bean 的两个实例并返回一个属性列表/数组,这两个实例的值不同?请发布一个小样本。 干杯 托马斯 最佳答案 BeanCompara
我是java新手。任何人都可以给出以下类声明的含义 public class ListNode, V> { K key; V value; ListNode next;
我需要用 C 语言计算和比较 3 种不同大小(100 * 100、1000 * 1000 和 10000 * 10000)的 2 个矩阵相乘的执行时间。我编写了以下简单代码来为 1000 * 1000
当我在 ACCESS 2007 中运行以下 SQL 时 Select Location, COUNT(ApartmentBuildings) AS TotalIBuildingsManaged Fro
根据我对互斥锁的了解——它们通常提供对共享资源的锁定功能。因此,如果一个新线程想要访问这个锁定的共享资源——它要么退出,要么必须不断轮询锁(并在等待锁时浪费处理器周期)。 但是,监视器具有条件变量,它
通常在编程中,不应该比较浮点数据类型是否相等,因为存储的值通常是近似值。 由于两个非整数 Oracle NUMBER 值的存储方式不同(以 10 为基数),是否可以可靠地比较它们是否相等? 最佳答案
使用 PowerShell 时,我们偶尔会比较不同类型的对象。一个常见的场景是 $int -eq $bool (即其中 0 -eq $false 、 0 -ne $true 和任何非零值仅等于真,但不
#include #define MAX 1000 void any(char s1[], char s2[], char s3[]); int main() { char string1[
我想比较两个日期。 从这两个日期中,我只使用 ToShortDateString() 获取日期组件, 如下所示。现在的问题是当我比较两个日期时。它的 throw 错误—— "Operator >= c
用户输入一个数字( float 或整数),并且它必须大于下限。 这是从 UITextField 获取数字的代码: NSNumberFormatter * f = [[NSNumberFormatter
我已经摆弄这段代码大约一个小时了,它让我难以置信。我认为解决方案相当简单,但我似乎无法弄清楚。无论如何,这里去。我制作了一个 javascript 函数来检查用户输入的字符,以便它只能接受 7 个字符
我不太明白为什么当我们在不覆盖 equals 的情况下比较具有相同类属性的两个实例时方法,它将给出 false .但它会给出 true当我们比较一个案例类的两个实例时。例如 class A(val
我是一名优秀的程序员,十分优秀!