Cod sursa(job #1896862)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 28 februarie 2017 22:37:00
Problema Sortare prin comparare Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 1.75 kb
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package merge.sort;

import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

class MergeSort {

    static int v[];
    static int n = -1;
    
    public static void interclasare(int p, int m, int q){
        int r[] = new int[n];
        int i = p, j = m+1, k = -1;
        while(i <= m && j <= q)
            if(v[i] < v[j])
                r[++k] = v[i++];
            else
                r[++k] = v[j++];
        while(i <= m)
            r[++k] = v[i++];
        while(j <= q)
            r[++k] = v[j++];
        for (int w = p; w <= q; ++w)
            v[w] = r[w-p];
    }
    
    public static void mergeSort(int p, int q){
        if(q > p){
            int m = (p+q)/2;
            mergeSort(p, m);
            mergeSort(m+1, q);
            interclasare(p, m, q);
        }
    }
    
    public static void main(String[] args) {
        
        try{
            File fin = new File("algsort.in");
            Scanner sc = new Scanner(fin);
            n = sc.nextInt();
            v = new int[n];
            for (int i = 0; i < n; ++i)
                v[i] = sc.nextInt();
            sc.close();
        }catch(Exception e){
            System.out.println("yea boi, ya fuckd");
        }
        
        mergeSort(0, n-1);
        
        try{
            PrintWriter fout = new PrintWriter("algsort.out");
            for (int i = 0; i < n; ++i)
                fout.print(v[i] + " ");
            fout.println();
            fout.close();
        }catch(Exception e){
            System.out.println("I am out of witty texts");
        }
        
    }
    
}