Sorting a time intervals

后端 未结 5 868
逝去的感伤
逝去的感伤 2021-01-27 12:25

I am giving a time interval in the form of two arrays.

A[0]=  2  B[0]=3
A[1]=  9  B[1]=11
A[2] = 5 B[2]=6
A[3] = 3 B[3]=10

I want to sort the i

5条回答
  •  温柔的废话
    2021-01-27 13:03

    It can be done straight, since you dont show what have you tried so far I just give you the algorithm:

    for j = 1 to n
        for i = i+1 to n
            if(A[i]>A[j]){
                swap(A[i],A[j])
                swap(B[i],B[j])
            }
    

    you can easily convert it to java code.

    this algorithm is buble sort if you want better algorithm use this wiki link to improve your time.

    As DwB want here is merge sort full java code that do what you want. I got merge sort algorithm from here and modify to satisfy your need. also you could see the working version on Ideone

    Merge Sort:

    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    class Ideone
    {
        private int[] A;
        private int[] B;
        private int[] helperA;
        private int[] helperB;
    
        private int length;
    
        public static void main (String[] args){
            int[] As = {2,9,5,3};
            int[] Bs = {3,11,6,10};
            new Ideone().sort(As,Bs);
        }
    
        public void sort(int[] As , int[] Bs) {
            A = As;
            B = Bs;
            length = A.length;
            this.helperA = new int[length];
            this.helperB = new int[length];
            mergesort(0, length - 1);
            for(int i = 0 ; i

提交回复
热议问题