繁体   English   中英

Java和数组-插入按升序排序

[英]Java and Arrays - Insertion sort in ascending order

所以我需要读取带有值的txt文件...

31 70 5 71 140 187 162 98 153 8 109 103 145 157 27 23 136 54 19 168 114 25 139 129 94

这是我的代码,现在我可以使用插入排序算法将值按降序排序。 但是,我还想知道如何更改插入排序方法,以将值升序排序。

import java.io.*;
import java.util.*;

public class Lab3
{
public static void main (String[] args) throws Exception
{
    if (args.length < 1)
    {
        System.out.println( "Fatal Error. Enter a filename on the command line!\n");

        System.exit(0);
    }

    int[] arr = new int[30];  
    int cnt=0;

    Scanner infile = new Scanner( new FileReader(args[0]) );
    while ( infile.hasNextInt() )
    {
        insertInOrder( arr, cnt, infile.nextInt() );
        ++cnt;  // INCR COUNT AFTER EVERY INSERTION
        printArray( arr, cnt ); // THEN PRINT ARRAY AFTER EVERY INSERTION
    }
    infile.close();

} // END main

// ======================================================================
//                  M    E   T    H    O    D   S
// ======================================================================


// YOU MUST FILL IN THIS METHOD
static void insertInOrder( int[] arr, int count, int newVal )
{
    arr[count] = newVal; //This appends the number
        for( count = 1; count<arr.length; count++)
        {
            int leftVal = count;
            newVal = arr[count];

                while((leftVal > 0) && (arr[leftVal-1]<newVal))
                {
                        arr[leftVal] = arr[leftVal-1];
                        leftVal--;
                }
                arr[leftVal] = newVal;
        }
}

// USE THIS METHOD AS GIVEN: DO NOT CHANGE
private static void printArray( int[] array, int count )
{
    for( int i=0 ; i<count ;++i )
        System.out.printf("%-4d",array[i] );  // "%-4d" means print arr[i] in 4 spaces left justified
        System.out.println();
}

} 
static void insertInOrder( int[] arr, int count, int newVal )
{
    arr[count] = newVal; //This appends the number
        for( count = 1; count<arr.length; count++)

在这里,您正在混合使用称为count的不同变量。 一个是输入参数,另一个是for循环的局部变量。 将for循环更改为:

for( int i = 1; i<count; i++) // you need to loop only till the newest index just added.

至于从降序转换为升序,然后在您的降序算法有效的情况下,您只需要更改比较运算符即可:

while((leftVal > 0) && (arr[leftVal-1]>newVal))
                                      ^

您可以将值放在这样的NavigableSet中

//for descending sort
   NavigableSet<Integer> descSet = new TreeSet<Integer>().descendingSet();
//for asc sort
      NavigableSet<Integer> ascSet = new TreeSet<>();

您可以这样使用:

List unsortedList = Arrays.asList(<<Your ARRAY>>);
Collections.sort(unsortedList, Collections.reverseOrder());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM