目前我已經通過文件迭代,但現在我想用快速排序的排序輸出。我創建了一個與本地數組一起工作的quickSort/partition類,但我想知道如何將它與其他類中的文件一起使用。我想做一些事情,比如按人口排序,按字母順序排列城市,按緯度排序。通過在Java中使用
這裏是一些文件是我的工作:
ad,Andorra La Vella,07,20430,42.5,1.5166667
ad,Canillo,02,3292,42.5666667,1.6
ad,Encamp,03,11224,42.5333333,1.5833333
ad,La Massana,04,7211,42.55,1.5166667
ad,Les Escaldes,08,15854,42.5,1.5333333
ad,Ordino,05,2553,42.55,1.5333333
ad,Sant Julia De Loria,06,8020,42.4666667,1.5
ae,Abu Dhabi,01,603687,24.4666667,54.3666667
ae,Dubai,03,1137376,25.2522222,55.28
我的代碼:
public class City {
String countrycode;
String city;
String region;
int population;
double latitude;
double longitude;
public City(String countrycode, String city, String region, int population, double latitude, double longitude) {
this.countrycode = countrycode;
this.city = city;
this.region = region;
this.population = population;
this.latitude = latitude;
this.longitude = longitude;
}
public String toString() {
return this.city + "," + this.population + "," + this.latitude + "," + this.longitude;
}
}
public class Reader {
In input = new In("file:world_cities.txt");
public static City cityInfo;
public static void main(String[] args) {
// open file
In input = new In("world_cities.txt");
try {
// write output to file
FileWriter fw = new FileWriter("cities_out.txt");
PrintWriter pw = new PrintWriter(fw);
int line = 0;
// iterate through all lines in the file
while (line < 47913) {
// read line
String cityLine = input.readLine();
// create array list
ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(",")));
// increase counter
line += 1;
// create variables for the object
String countrycode = cityList.get(0);
String city = cityList.get(1);
String region = cityList.get(2);
int population = Integer.parseInt(cityList.get(3));
double latitude = Double.parseDouble(cityList.get(4));
double longitude = Double.parseDouble(cityList.get(5));
// create instance
cityInfo = new City(countrycode, city, region, population, latitude, longitude);
System.out.println(cityInfo);
// print output to file
pw.println(cityInfo);
}
// close the file
pw.close();
}
// what is printed when there is an error when saving to file
catch (Exception e) {
System.out.println("ERROR!");
}
// close the file
input.close();
}
}
public class QuickSort3 {
public static void main(String[]args) {
int[] array = {4, 77, 98, 30, 20, 50, 77, 22, 49, 2}; // local array that works with the quicksort
quickSort(array,0,array.length - 1);
System.out.println(Arrays.toString(array));
}
public static void quickSort(int[] a, int p, int r)
{
if(p<r)
{
int q = Partition(a, p,r);
quickSort(a, p, q-1);
quickSort(a, q+1, r);
}
}
private static int Partition(int[] a, int p, int r)
{
int x = a[r];
int i = p-1;
int temp=0;
for(int j=p; j<r; j++)
{
if(a[j]<=x)
{
i++;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp = a[i+1];
a[i+1] = a[r];
a[r] = temp;
return (i+1);
}
}
什麼是您的排序邏輯是什麼?國家,城市,地區? –
如果你給你的快速排序法類型的附加參數'Comparator'或'BiPredicate'它可以用於任何你想要的順序任意類型的數組排序。 – SpiderPig