SORTING FILES ARRAY BY LASTMODEFIEDTIME

naomi burke

Total Post:28

Points:196
Posted by  naomi burke
 643  View(s)
Ratings:
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?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Sorting Files Array by LastModefiedTime

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!