Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java ME (J2ME) > Сортировка данных


Автор: Samuil 11.8.2006, 01:56
Здравствуйте форумовцы! Возникла следующая проблема: Есть текстовый документ, в котором есть данные, они расположены не в алфавмтном порядке, нужно сделать чтоб программа сама их сортировала и показывала на дисплей.
Вот пример текстового документа:

ДЖОРДЖ 
ГЕРМАН 
ЕЛИЗАР 
АГАФЬЯ
<исходник>

<а надо так:>
АГАФЬЯ
ГЕРМАН 
ДЖОРДЖ 
ЕЛИЗАР 

 К сожалению пока неимею опыта работы. Вот еще где можно найти(скачать) хорошую книжку по программированию на java2ME, желательно на русском, но если книга действительно стоящая то и на английском подайдет.

Автор: javastic 11.8.2006, 09:51
Зайди на форум Алгоритмы (на Винграде даже есть) и поищи там алгоритм сортировки.
А книги есть у меня на сайте http://vitalich.com/j2me/books2/

Там будет список книг, просто поставь имя файла в УРЛе и сможешь скачать.
Просьба на лево и на право ссылку не раздавать.  smile 

Автор: Dancer 11.8.2006, 11:19
если в этой гадости порыться, то можно разобраться, что к чему.
Так тебе будут некоторые вещи лишние, думаю повыковыриваешь. И..... у меня в векторах всё это добро хранилось, так что либо свои данные пихай в вектор, либо как то код перелапачивай (ну там массивы строк или ещё что придумаешь)
вызов осуществляется как:
                Ordering.sort(SearchManager.getSearchResultVector()); 
ну, у тебя будет свой вектор (или чего там придумаешь)

Код


import java.util.Vector;

public class Ordering {

    public static final String [] arrayOfSortingField = {
        "Avalaibility",
        "File Name",
        "File Size",
        "File Type",
        "Bitrate"
    };

    public static final String[] arrayOfSortingType = {
        "ASC",
        "DESC"
    };

    public static final int AVALIABLE_FIELD = 0;
    public static final int NAME_FIELD = 1;
    public static final int SIZE_FIELD = 2;
    public static final int TYPE_FIELD = 3;
    public static final int BITRATE_FIELD = 4;

    public static final int SORT_BY_ASC =0;
    public static final int SORT_BY_DESC =1;

    private static int currentSortField = AVALIABLE_FIELD;
    private static int currentSortType = SORT_BY_DESC;

    public static int getSortField() {
        return currentSortField;
    }

    public static int getSortType() {
        return currentSortType;
    }

    private static void quickSortForStringField(Vector results, int lo0, int hi0) { //throws Exception {
        int lo = lo0;
        int hi = hi0;
        String mid;

        if ( hi0 > lo0) {

        /* Arbitrarily establishing partition element as the midpoint of
         * the array.
        */

            mid = ((SearchResult)results.elementAt(( lo0 + hi0 ) / 2 )).getFieldValue(getSortField());

         // loop through the array until indices cross
            while( lo <= hi ) {
            /* find the first element that is greater than or equal to
             * the partition element starting from the left Index.
             */
//                while( ( lo < hi0 ) && ( ((SearchResult)results.elementAt(lo)).getFieldValue(getSortField()).compareTo(mid) < 0 ))
                while( ( lo < hi0 ) && ( compareStrings(((SearchResult)results.elementAt(lo)).getFieldValue(getSortField()), mid) < 0 ))
                    ++lo;

            /* find an element that is smaller than or equal to
             * the partition element starting from the right Index.
             */
//                while( ( hi > lo0 ) && ( ((SearchResult)results.elementAt(hi)).getFieldValue(getSortField()).compareTo(mid) > 0))
                while( ( lo < hi0 ) && ( compareStrings(((SearchResult)results.elementAt(hi)).getFieldValue(getSortField()), mid) > 0 ))
                    --hi;

            // if the indexes have not crossed, swap
                if( lo <= hi ) {
                    swap(results, lo, hi);
                    ++lo;
                    --hi;
                }
            }

         /* If the right index has not reached the left side of array
          * must now sort the left partition.
          */
            if( lo0 < hi )
                quickSortForStringField(results, lo0, hi );

         /* If the left index has not reached the right side of array
          * must now sort the right partition.
          */
            if( lo < hi0 )
                quickSortForStringField(results, lo, hi0 );

        }
    }

    private static void quickSortForIntegerField(Vector results, int lo0, int hi0) { //throws Exception {
        int lo = lo0;
        int hi = hi0;
        long mid;

        if ( hi0 > lo0) {

            mid = Long.parseLong(((SearchResult)results.elementAt(( lo0 + hi0 ) / 2 )).getFieldValue(getSortField()));

         // loop through the array until indices cross
            while( lo <= hi ) {
                while( ( lo < hi0 ) && ( Long.parseLong(((SearchResult)results.elementAt(lo)).getFieldValue(getSortField())) < mid ))
                    ++lo;

                while( ( hi > lo0 ) && ( Long.parseLong(((SearchResult)results.elementAt(hi)).getFieldValue(getSortField())) > mid))
                    --hi;

            // if the indexes have not crossed, swap
                if( lo <= hi ) {
                    swap(results, lo, hi);
                    ++lo;
                    --hi;
                }
            }

            if( lo0 < hi )
                quickSortForIntegerField(results, lo0, hi );

            if( lo < hi0 )
                quickSortForIntegerField(results, lo, hi0 );
        }
    }

    private static void swap(Vector results, int i, int j) {
        SearchResult  T;
        T = (SearchResult) results.elementAt(i);
        results.setElementAt(results.elementAt(j),i);
        results.setElementAt(T,j);
    }

    public static void sort(Vector results) { //throws Exception {
        if(currentSortField == NAME_FIELD || currentSortField == TYPE_FIELD ) {
            quickSortForStringField(results, 0, results.size() - 1);
        } else {
            quickSortForIntegerField(results, 0, results.size() - 1);
        }
        SearchManager.wasChangedSearchedFilesList(); // на это не обращай внимание, я туту просто дёргаю перерисовку листа после пересортировки данных
    }

    public static void setSortField(int index) {
        currentSortField = index;
    }

    public static void setSortType(int index) {
        currentSortType = index;
    }

    private static int compareStrings(String str1, String str2) {
        if(str1.toUpperCase().charAt(0) == str2.toUpperCase().charAt(0)) {
//        if(str1.toLowerCase().charAt(0) == str2.toLowerCase().charAt(0)) {
            return str1.compareTo(str2);
        } else {
            return str1.toUpperCase().compareTo(str2.toUpperCase());
//            return str1.toLowerCase().compareTo(str2.toLowerCase());
        }
    }
}


Автор: Samuil 11.8.2006, 12:49
Нихилый кодик! Dancer, сейчас попробую smile 

Автор: Dancer 11.8.2006, 17:41
да, я тут только что пробежался глазами, ты это SearchResult тогда на String поменяй (ну, не смотрел я его, не смотрел. Как есть, так и взял весь класс. Реализовывал то давно smile )

Автор: redrick 15.8.2006, 16:25
сдается мне основная проблема будет считать построчно из файлика )
думаю вот это поможет
Код

private InputStream getStream() {
       InputStream is =
                getClass().getResourceAsStream(filename);
       return is;
    }

private void loadResources() {
        InputStream is = getStream(); // возвращает поток с сообщениями для текущего языка телефона

        try {
            readChar(is); // 0xFEFF нам не нужен
            strings = new Hashtable();

            StringBuffer buf = new StringBuffer(32);

            while(true) {
                
                if(ch == -1) {
                    break;
                }

                String value = buf.toString().trim();
                buf.delete(0, buf.length());

                strings.put(value);

                // доходим до конца строки
                while((ch = readChar(is)) != -1 && ch != 0xA && ch != 0xD) {
                }
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)