Cod sursa(job #1988911)

Utilizator SilviuIIon Silviu SilviuI Data 5 iunie 2017 10:47:54
Problema Sortare prin comparare Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 2.79 kb
package Sorting;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PrintWriter;

public class Main
{
   public static int pos = 0;
   public static int[] t; 
   
   public static int readInt(String s)
   {
      int ans = 0;
      
      while (pos < s.length() && s.charAt(pos) != ' ') {
         
         ans = ans * 10 + (s.charAt(pos) - 48);
         
         pos++;
         
      }
      
      pos++;
      
      return ans;
   }
   
   public static void merge(int[] t, int st, int dr, int m)
   {
      int current1 = st;
      int current2 = m + 1;
      int posToInsert = 0;
      
      int[] arr = new int[dr - st + 1];
      
      while (current1 <= m && current2 <= dr) {
         
         if (t[current1] < t[current2]) {
            
            arr[posToInsert] = t[current1]; current1++;
         } else {
            
            arr[posToInsert] = t[current2]; current2++;
            
         }
         
         posToInsert++;
         
      }
      
      while (current1 <= m) { arr[posToInsert] = t[current1]; current1++; posToInsert++; }
      
      while (current2 <= dr) { arr[posToInsert] = t[current2]; current2++; posToInsert++; }
      
      for (int i = st; i <= dr; i++) t[i] = arr[i - st];
   }
   
   public static void mergeSort(int[] t, int st, int dr)
   {
      if (st >= dr) return;
      
      int m = (st + dr) / 2;
      
      mergeSort(t, st, m);
      mergeSort(t, m + 1, dr);
      
      merge(t, st, dr, m);
   }
   
   public static void main(String[] args)
   {
      try
      {
         BufferedReader in = new BufferedReader(new FileReader("algsort.in"));
         PrintWriter out = new PrintWriter(new FileWriter("algsort.out"));
         
         String f1 = in.readLine();
         String f2 = in.readLine();
         
         pos = 0;
         
         int n = readInt(f1);
         
         pos = 0;
         
         t = new int[n];
         
         for (int i = 0; i < n; i++) t[i] = readInt(f2);
         
         mergeSort(t, 0, t.length - 1);
         
         String ans = "";
         
         for (int i = 0; i < n; i++) 
            if (i < n - 1) ans = ans + t[i] + " "; else
               ans = ans + t[i];
         
         out.write(ans);
         
         out.close();
         
      }
      catch (FileNotFoundException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      
      
   }
}