提问者:小点点

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


所以我需要读取一个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();
}

} 

共3个答案

匿名用户

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

这里你混合到不同的变量称为计数。一个是输入参数,另一个是本地为循环的变量。将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());