Home > DeveloperSection > Forums > Sorting Files Array by LastModefiedTime
naomi burke
naomi burke

Total Post:28

Points:196
Posted on    November-27-2015 6:33 AM

 Android Android  Java  Sorting 
Ratings:


 1 Reply(s)
 290  View(s)
Rate this:
I want to Sort a Files Array by lastModefiedTime from the oldest to the newest ( first Element must be the Oldest and the Last Element the newest).

i wrote this Methods but it didnt work!!

private static void swap(File[] files,int a, int b){
    File h = files[a];
    files[a]=files[b];
    files[b]=h;
}
public static void fillBoxList(String path){


    File dir = new File(path);
    File[] files = dir.listFiles();
    if (files != null) {
        //Box.addToFilesArray(directoryListing[0]);
// print the List before Sorting 
        for(int i =0;i<dfiles.length;i++){
            Log.i("LastModDate", new Date(directoryListing[i].lastModified())+"");
        }
//Beginn of Sorting
        for (int i =1;i<files.length;i++) {
            Date lastModdate1 = new Date(files[i-1].lastModified());
            Date lastModDate2 = new Date(files[i].lastModified());
                 if(lastModdate1.compareTo(lastModDate2)>1){
                     swap(files,i-1,i);
                 }
        }
// print the List after Sorting
        for(int i =0;i<directoryListing.length;i++){
            Log.i("SortedLastModDate", new Date(directoryListing[i].lastModified())+"");
        }
    } else {
        Log.e("DircError","directory dont exists");
    }
}

can you tell me please what i did wrong?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    November-27-2015 6:48 AM

Your sort algorithm is actually wrong. There should be two loops in a Bubble sort

while (true){
    boolean swapped = false;
    for (int i =1;i<files.length;i++) {
        Date lastModdate1 = new Date(files[i-1].lastModified());
        Date lastModDate2 = new Date(files[i].lastModified());
        if(lastModdate1.compareTo(lastModDate2)>1){
              swap(files,i-1,i);
              swapped = true;
        }
    }
    if ( !swapped )
      break;
}

Don't want to miss updates? Please click the below button!

Follow MindStick