Question
Answer with simple java code and comments
This homework deals with the problem of partitioni
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the required program along with its output. Please see the comments against each line to understand the step.

import java.util.Arrays;

class Test{
    public static void main(String[] args) {
        double result[] = partition(new double[]{10,7,45,-44,33,1});
        System.out.println("Result Array : "+Arrays.toString(result));
    }

    public static double[] partition(double a[]){
        double[] lesser = new double[a.length]; //declare lesser array
        double[] greater = new double[a.length];    //declare greater array
        double pivot = a[0];    //get the pivot

        int li = 0, gi = 0; //initialize lesser and greater indexes
        for(int i=1; i<a.length; i++){  //iterate through all elements in a
            if(a[i]<pivot){ //if current iteration element is less than pivot, add it to lesser array and update the index li
                lesser[li] = a[i];
                li++;
            } else if(a[i] >= pivot){   //else if current iteration element is greater than or equal to pivot, add it to greater array and update the index gi
                greater[gi] = a[i];
                gi++;
            }
        }

        double[] result = new double[a.length]; //initialize the result array
        int k=0;
        for(int i=0; i<li; i++) {   //iterate through index 0 to li(will contain no:of elements in lesser array) of lesser array and add it to new result array
            result[k++] = lesser[i];
        }
        result[k++] = pivot;    //add pivot element to the result array
        for(int i=0; i<gi; i++) {   //iterate through index 0 to gi(will contain no:of elements in greater array) of greater array and add it to new result array
            result[k++] = greater[i];
        }
        return result;  //return the result array
    }
}

--------------------------------------------------------------

OUTPUT:

Result Array : [7.0, -44.0, 1.0, 10.0, 45.0, 33.0]

Add a comment
Know the answer?
Add Answer to:
Answer with simple java code and comments This homework deals with the problem of partitioning an...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT