Java和数组 - 按升序排序

时间:2014-02-08 15:56:05

标签: java arrays algorithm sorting

所以我需要读入带有值的文本文件...

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();
}

} 

3 个答案:

答案 0 :(得分:1)

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))
                                      ^

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

您可以这样使用:

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