[英]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.