Cod sursa(job #2063756)

Utilizator alexb97Alexandru Buhai alexb97 Data 11 noiembrie 2017 14:10:09
Problema Sortare prin comparare Scor 40
Compilator java Status done
Runda Arhiva educationala Marime 2.14 kb

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args)
    {
        Scan cin;
        PrintWriter cout;
        try
        {
            cin = new Scan("algsort.in");
            cout = new PrintWriter("algsort.out");
            int n = cin.nextInt();
            int x;
            List<Integer> arr = new ArrayList<>();

            for(int i = 0; i < n; ++i)
            {
                x = cin.nextInt();
                arr.add(x);
            }
            BS(arr);
            for(int i = 0; i < n; ++i)
            {
                cout.print(arr.get(i)+ " ");
            }
            cin.close();
            cout.close();

        }
        catch (Exception ex)
        {
            System.out.println(ex.toString());
        }

    }

    public static <T extends Comparable<T>> void BS(List<T> arr)
    {
        boolean swap;

        int size =arr.size()-1;
        do
        {
            swap = false;
            for (int i = 0; i < size; ++i)
            {
                int comp = arr.get(i).compareTo(arr.get(i+1));
                if (comp > 0)
                {
                    T temp = arr.get(i);
                    arr.set(i,arr.get(i+1));
                    arr.set(i+1,temp);
                    swap = true;
                }
            }
            size--;
        }while (swap);

    }

    public static class Scan {
        private BufferedReader bufferedReader;
        private StringTokenizer stringTokenizer;

        Scan(String filename) throws FileNotFoundException
        {
            bufferedReader = new BufferedReader(new FileReader(filename));
        }
        private String next() throws IOException
        {
            while(stringTokenizer == null || !stringTokenizer.hasMoreElements())
            {
                stringTokenizer = new StringTokenizer(bufferedReader.readLine());

            }
            return stringTokenizer.nextToken();
        }
        int nextInt() throws IOException
        {
            return Integer.parseInt(next());
        }
        void close() throws IOException
        {
            bufferedReader.close();
        }



    }

}