排序比较计数器

2024-03-10

我有这段代码,可以对填充有随机数的数组进行排序,并计算完成排序所需的数字比较。我正在使用排序方法选择冒泡和合并排序。我有选择和气泡的计数器,但没有合并的计数器,我不知道把它放在哪里。这可能是一个简单的答案,但我就是无法让它发挥作用。

Code:

/***********************************************************************
     * 
     * Selection Sort:
     * Reads in the array and then searches for the largest number. 
     * After it finds the largest number, it then swaps that number with the
     * last number of the array
     * Precondition: takes in an array of "n" items, which in this particular
     * case is 2000, 4000, 6000, 8000, and 10000 random items in an array
     * Postcondition: all numbers are sorted in ascending order
     * 
     **********************************************************************/
    public static int SelectionSort (int[] intArray) {

        //Set initial count of comparisons at 0         
        comparisons= 0;        //Number of swaps made


        for(int last = intArray.length - 1; last > 0; last--) {

            int largestIndex = last;    //Int which places the largest number at the end of the array

            // Find largest number
            for(int i = 0; i < last; i++) {

                //if i > the last number
                if (intArray[i] > intArray[largestIndex]){
                    largestIndex = i;       //switch the last number and i
                } // end if

                //Comparison+1 
                comparisons++;

            } // end for

            // Swap last element with largest element
            int largest = intArray[last];
            intArray[last] = intArray[largestIndex];
            intArray[largestIndex] = largest;

        }
        //Return comparison counter
        return comparisons;
    }

    /***********************************************************************
     * 
     * Bubble Sort:
     * Takes an array of random integers and sorts them by comparing adjacent
     * numbers to one another. Whichever the larger adjacent number, Bubble
     * Sort switches it towards the back end of the adjacent numbers. It does
     * this until the list is fully sorted.
     * Precondition: takes in a random array of integers
     * Postcondition: array is sorted from smallest to largest
     * 
     **********************************************************************/
    public static int BubbleSort (int[] intArray) {

        //Instance Variables    
        int n = intArray.length;
        //boolean swap;   
        comparisons = 0;

        //swap = false;
        //for i starts at 0, when i is less than array length, i++ until reach array length
        for(int i=0; i < n; i++) {

            for(int j=1; j < (n-i); j++) {

                if(intArray[j-1] > intArray[j]) {

                    //Swap the elements
                    int temp = intArray[j];
                    intArray[j] = intArray[j+1];
                    intArray[j+1] = temp;
                    //swap = true;

                } 
            //comparisons get +1 until the for loop is done sorting
            comparisons++;
           }  //End for loop
        }
        //Return the comparison counter
         return comparisons;
    }

    /************************************************************************************
     * 
     * Merge Sort:
     * This method takes a random array and splits it in half. Once the array is
     * split in half, it creates a temp0rary array. This temporary array is built by
     * the method searching the two halves of the original array and puts the information
     * in order stored in the temporary array. Once all the numbers are in order, the 
     * temporary array is then copied back to the original array.
     * Precondition: take in an array of random integers
     * Postcondition: return the random array sorted in ascending order
     * 
     **********************************************************************************/
    public static int mergeSort(int[] intArray) {

        if(intArray.length >= 2) {

            int mid = intArray.length / 2;
            //Create 2 arrays to store half of the data in each
            int[] first = new int[mid];     //holds first half of array
            int[] second = new int[intArray.length - mid];  //holds second half of array

            for(int i = 0; i < first.length; i++) { 
                first[i] = intArray[i];     
            }

            for(int i = 0; i < second.length; i++) {
                second[i] = intArray[mid+i];
            }

            mergeSort(first);
            mergeSort(second);
            merge(first, second, intArray);     //Merge all together

        }

        return comparisons;
    }

    //merging first and second halves of mergeSort array
    public static int merge(int[] first, int[] second, int[] intArray) {

        int iFirst = 0;
        int iSecond = 0;
        int i = 0; 

        //moving the smaller element into intArray
        while(iFirst < first.length && iSecond < second.length) {

            comparisons++;

            if(first[iFirst] < second[iSecond]) {
                intArray[i] = first[iFirst];
                iFirst++;
            }

            else {
                intArray[i] = second[iSecond];
                iSecond++;
            }
            i++;
        }


        //copying the remaining of first array
        while(iFirst < first.length) {
            intArray[i] = first[iFirst];
            iFirst++; i++; 
        }

        //copying the remaining of second array
        while(iSecond < second.length)
        {
            intArray[i] = second[iSecond];
            iSecond++; i++; 
        } 

        return comparisons;
    }

    /**************************************************************************************
     * Instance methods:
     * These methods perform actions to the array.
     * 
     * copyArray()--makes a copy of the array to be used in the main class
     *              so that each method is able to create the same array
     * 
     * printArray()--prints out the array for display
     * 
     * randomArray()--creates a random integer array used by all three sorting methods
     * 
     **************************************************************************************/

    public static int[] copyArray(int[] intArray) {

        //Constructor that creates copyArray
        int[] copyArray = new int[intArray.length];     //siz equal to the length of the array

        for(int i = 0; i < intArray.length; i++){
            copyArray[i] = intArray[i];
        } // end for

        return copyArray;

    } // end copyArray

    //Prints out array
    public static void printArray(int[] intArray){
        //Preconditions
        //  Input: unsorted integer array   
        //  Assumptions: array is full
        //Postconditions
        //  Output: none
        //  Actions: array is displayed on screen

        System.out.print("Array==> ");
        for(int i = 0; i < intArray.length; i++){
            System.out.print(intArray[i] + " ");
        } // end for

        System.out.println(" ");

    } // end printArray

    //Creates a random array that is used for each sorting method
    public static int[] randomArray(int array, double range){
        //Preconditions
        //  Input: size of array(n), range of integers (0 to range)
        //  Assumptions: none
        //Postconditions
        //  Output: array of random integers 0 to floor(range) 
        //  Actions: none

        int[] intArray = new int[array];

        for(int i = 0; i < array; i++){
            intArray[i] = (int)(Math.random() * range);
        } // end for

        return intArray;

    } // end randomIntArray


}

当执行以下几行时(或之前):

  • if (int Array[in] > int Array[最大索引]){
  • if(intArray[j-1] > intArray[j]) {
  • if(第一[iFirst]

您的 mergeSort 方法使用递归。因此,它需要采用比较参数,并将其传递给每个后续方法调用,并再次接收返回的结果值。

public static int mergeSort(int[] intArray, int comparisons) {

    if(intArray.length >= 2) {

        int mid = intArray.length / 2;
        //Create 2 arrays to store half of the data in each
        int[] first = new int[mid];     //holds first half of array
        int[] second = new int[intArray.length - mid];  //holds second half of array

        for(int i = 0; i < first.length; i++) { 
            first[i] = intArray[i];     
        }

        for(int i = 0; i < second.length; i++) {
            second[i] = intArray[mid+i];
        }

        comparisons = mergeSort(first, comparisons);
        comparisons = mergeSort(second, comparisons);
        comparisons = merge(first, second, intArray, comparisons);     //Merge all together

    }

    return comparisons;
}

//merging first and second halves of mergeSort array
public static int merge(int[] first, int[] second, int[] intArray, int comparisons) {

    int iFirst = 0;
    int iSecond = 0;
    int i = 0; 

    //moving the smaller element into intArray
    while(iFirst < first.length && iSecond < second.length) {

        comparisons++;

        if(first[iFirst] < second[iSecond]) {
            intArray[i] = first[iFirst];
            iFirst++;
        }

        else {
            intArray[i] = second[iSecond];
            iSecond++;
        }
        i++;
    }


    //copying the remaining of first array
    while(iFirst < first.length) {
        intArray[i] = first[iFirst];
        iFirst++; i++; 
    }

    //copying the remaining of second array
    while(iSecond < second.length)
    {
        intArray[i] = second[iSecond];
        iSecond++; i++; 
    } 

    return comparisons;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

排序比较计数器 的相关文章

  • 如果测试用例失败,Selenium Web 驱动程序无法关闭 Firefox 实例

    我各位 我正在使用 junit 和 selenium web 驱动程序 2 28 问题是 如果我运行成功的测试用例 Web 驱动器能够关闭 Firefox 实例 但是当测试用例失败时 Selenium Web 驱动器无法关闭 Firefox
  • 线程自动利用多个CPU核心?

    假设我的应用程序运行 2 个线程 例如渲染线程和游戏更新线程 如果它在具有多核 CPU 当今典型 的移动设备上运行 我是否可以期望线程在可能的情况下自动分配给不同的核心 我知道底层操作系统内核 Android linux内核 决定调度 我的
  • Android Studio 在编译时未检测到支持库

    由于 Android Studio 将成为 Android 开发的默认 IDE 因此我决定将现有项目迁移到 Android studio 中 项目结构似乎不同 我的项目中的文件夹层次结构如下 Complete Project gt idea
  • IntelliJ IDEA 创建的 JAR 文件无法运行

    我在 IntelliJ 中编写了一个跨越几个类的程序 当我在 IDE 中测试它时它运行良好 但是 每当我按照教程将项目制作成 jar 可执行文件时 它就不会运行 双击 out 文件夹中的文件时 该文件不会运行 并显示 无法启动 Java J
  • 使用 ANTLR 为 java 源代码生成抽象语法树

    如何使用 ANTLR 从 java src 代码生成 AST 有什么帮助吗 好的 步骤如下 前往ANTLR站点 http www antlr org 并下载最新版本 下载Java g和JavaTreeParser g文件来自here htt
  • 一种使用 Java Robot API 和 Selenium WebDriver by Java 进行文件上传的解决方案

    我看到很多人在使用 Selenium WebDriver 的测试环境中上传文件时遇到问题 我使用 selenium WebDriver 和 java 也遇到了同样的问题 我终于找到了解决方案 所以我将其发布在这里希望对其他人有所帮助 当我需
  • Spring Data 与 Spring Data JPA 与 JdbcTemplate

    我有信心Spring Data and Spring Data JPA指的是相同的 但后来我在 youtube 上观看了一个关于他正在使用JdbcTemplate在那篇教程中 所以我在那里感到困惑 我想澄清一下两者之间有什么区别Spring
  • 归并排序中的递归:两次递归调用

    private void mergesort int low int high line 1 if low lt high line 2 int middle low high 2 line 3 mergesort low middle l
  • 制作java包

    我的 Java 类组织变得有点混乱 所以我要回顾一下我在 Java 学习中跳过的东西 类路径 我无法安静地将心爱的类编译到我为它们创建的包中 这是我的文件夹层次结构 com david Greet java greeter SayHello
  • 尝试使用 Ruby Java Bridge (RJB) gem 时出现错误“无法创建 Java VM”

    我正在尝试实现 Ruby Java Bridge RJB gem 来与 JVM 通信 以便我可以运行 Open NLP gem 我在 Windows 8 上安装并运行了 Java 所有迹象 至少我所知道的 都表明 Java 已安装并可运行
  • 将多模块 Maven 项目导入 Eclipse 时出现问题 (STS 2.5.2)

    我刚刚花了最后一个小时查看 Stackoverflow com 上的线程 尝试将 Maven 项目导入到 Spring ToolSuite 2 5 2 中 Maven 项目有多个模块 当我使用 STS 中的 Import 向导导入项目时 所
  • 应用程序关闭时的倒计时问题

    我制作了一个 CountDownTimer 代码 我希望 CountDownTimer 在完成时重新启动 即使应用程序已关闭 但它仅在应用程序正在运行或重新启动应用程序时重新启动 因此 如果我在倒计时为 00 10 分钟 秒 时关闭应用程序
  • Tomcat 6找不到mysql驱动

    这里有一个类似的问题 但关于类路径 ClassNotFoundException com mysql jdbc Driver https stackoverflow com questions 1585811 classnotfoundex
  • 将 JSON 参数从 java 发布到 sinatra 服务

    我有一个 Android 应用程序发布到我的 sinatra 服务 早些时候 我无法读取 sinatra 服务上的参数 但是 在我将内容类型设置为 x www form urlencoded 之后 我能够看到参数 但不完全是我想要的 我在
  • Windows 上的 Nifi 命令

    在我当前的项目中 我一直在Windows操作系统上使用apache nifi 我已经提取了nifi 0 7 0 bin zip文件输入C 现在 当我跑步时 bin run nifi bat as 管理员我在命令行上看到以下消息 但无法运行
  • 如何配置eclipse以保持这种代码格式?

    以下代码来自 playframework 2 0 的示例 Display the dashboard public static Result index return ok dashboard render Project findInv
  • 如何测试 spring-security-oauth2 资源服务器安全性?

    随着 Spring Security 4 的发布改进了对测试的支持 http docs spring io spring security site docs 4 0 x reference htmlsingle test我想更新我当前的
  • 将 JTextArea 内容写入文件

    我在 Java Swing 中有一个 JTextArea 和一个 提交 按钮 需要将textarea的内容写入一个带有换行符的文件中 我得到的输出是这样的 它被写为文件中的一个字符串 try BufferedWriter fileOut n
  • KeyPressed 和 KeyTyped 混淆[重复]

    这个问题在这里已经有答案了 我搜索过之间的区别KeyPressedand KeyTyped事件 但我仍然不清楚 我发现的一件事是 Keypressed 比 KeyTyped 首先被触发 请澄清一下这些事件何时被准确触发 哪个适合用于哪个目的
  • 中断连接套接字

    我有一个 GUI 其中包含要连接的服务器列表 如果用户单击服务器 则会连接到该服务器 如果用户单击第二个服务器 它将断开第一个服务器的连接并连接到第二个服务器 每个新连接都在一个新线程中运行 以便程序可以执行其他任务 但是 如果用户在第一个

随机推荐

  • 超时已过。操作完成前超时时间已过或服务器未响应

    我不确定这是 VB NET 错误还是 SQL Server 错误 但我通过以下堆栈跟踪得到上述错误 SqlException 0x80131904 超时 已到期 超时时间已过 在操作完成之前 或者服务器没有响应 System Data Sq
  • Java Swing JTextArea 不工作

    我正在开发一款游戏 在此部分中 将打开一个新窗口来显示游戏说明 唯一的问题是 当 txt 文件超过 20 行时 JTextArea 只显示一行 我是这方面的新手 所以我不确定我错过了什么 谢谢 class Instruction exten
  • 如何使用 MediaRecorder 在 Android 中录制原始 AAC 音频文件? AAC_ADTS 不起作用

    我正在使用 Android MediaRecorder 录制 AAC 编码的音频文件 将输出格式设置为 MPEG 4 效果很好 但由于我的音频播放器既不支持 MPEG 4 也不支持 3GP 我尝试使用输出格式获取原始 AAC 文件AAC A
  • 如何在 REPL 中重新加载 clojure 文件

    无需重新启动 REPL 即可重新加载 Clojure 文件中定义的函数的首选方法是什么 现在 为了使用更新的文件 我必须 edit src foo bar clj 关闭 REPL 打开 REPL load file src foo bar
  • 为什么 ViewController 内的 tableView 的 reloadData 显示错误?

    我在视图控制器中有一个 tableView 但是 reloadData 不适用于 tableView Xcode 显示错误 thread1 exc bad instruction 我尝试将 reloadData 分配给其他方法 但结果是相同
  • JavaScript 中的 Number.sign()

    想知道是否有任何重要的方法可以找到数字的符号 符号函数 http en wikipedia org wiki Signum function 可能比明显的解决方案更短 更快 更优雅 var sign number gt 0 1 number
  • 如何使用Phonegap 3.0浏览并选择SD卡中的文件?

    通过Phonegap 3 0的API 当我使用 UI 单击链接或按钮时 我想浏览 SD 卡中的文件 例如 p Upload p 假设 browserFile 函数包含浏览功能 但需要 UI 实现 Or
  • 使用 AngularJS 指令嵌入 Vimeo 视频

    我在 AngularJS 应用程序中有一个部分 HTML 页面 我正在尝试向其中添加 vimeo 视频 该模板有一个图像和播放按钮 单击时会淡出以显示底层 iFrame 我还想要这个点击触发器来播放视频 这样就不必按两个播放按钮 我的部分页
  • 如何使用新值填充对象列表

    抱歉 我很好 菜鸟 我有一个项目类 class item ind Int freq Int gap Int 我有一个有序的整数列表 val listVar a toList 其中 a 是一个数组 我想要一个称为指标的项目列表 其中 ind
  • iOS7上如何设置NSString的背景cornerRadius

    我想在iOS7上设置NSString的背景cornerRadius 但是 NSString 没有层 请告诉我 如何在iOS7上设置NSString的背景cornerRadius example 您可以使用UITextView其子类为NSLa
  • Laravel 5 中 all() 和 toArray() 之间的区别

    当我管理需要转换为数组的集合时 我通常使用toArray 但我也可以使用all 我不知道这两个功能的区别 有人知道吗 如果它是 Eloquent 模型的集合 模型也会被转换为数组toArray col gt toArray 总之 它将返回
  • 如何在 python nltk 中获取 n-gram 搭配和关联?

    In 本文档 http nltk googlecode com svn trunk doc howto collocations html 有一个例子使用nltk collocations BigramAssocMeasures Bigra
  • 使用公共子字符串连接两个字符串?

    说我有弦 string1 Hello how are you string2 are you doing now 结果应该是这样的 Hello how are you doing now 我正在考虑使用不同的方式re和字符串搜索 最长公共子
  • 从每 n 行复制单元格

    我想从每个人的名字中获取名字这个谷歌电子表格 https docs google com spreadsheets d 1S3AyaWjES1Go NxFYryIDlo0humlvzU4 fbiwNIWwo0 edit usp sharin
  • 使用 Node 的 Google API 批量请求

    我注意到 Google 最近从他们的 Node 客户端删除了批量请求 https github com google google api nodejs client blob 0db674b7d3a04cf65e223f876cf7b3f
  • 使用专用网络从 Google Compute Engine 访问 Google Cloud SQL

    是否可以使用专用网络从 Google Compute Engine 访问 Google Cloud SQL Google Cloud SQL 似乎看到了 Google Compute Engine 实例的公共网络 IP 并且 Web 控制台
  • 在 React JS 中使用颜色控制时的警告

    我将 React JS 与 Babel 和 Webpack 一起使用 一切都与我的其他脚本 甚至使用颜色模块的脚本 一起正常工作 但是 我的脚本之一给了我以下错误 指定的值 不符合要求的格式 这 格式为 rrggbb 其中 rr gg bb
  • 无法更新 Xamarin for Visual Studio

    我最近不得不重新安装我的电脑 我重新安装了VS2015 Community 然后我从 www xamarin com download 安装了 Xamarin 每当我打开 Visual Studio 时都会收到以下通知 尽管当我点击它时什么
  • remove() 方法太慢

    我在读取内存痕迹时遇到问题 我已阅读它并将页面及其参考保存在地图上 地图结构 Map
  • 排序比较计数器

    我有这段代码 可以对填充有随机数的数组进行排序 并计算完成排序所需的数字比较 我正在使用排序方法选择冒泡和合并排序 我有选择和气泡的计数器 但没有合并的计数器 我不知道把它放在哪里 这可能是一个简单的答案 但我就是无法让它发挥作用 Code