Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Sorting an array without using the method sort()

  1. #1
    Junior Member
    Join Date
    Oct 2021
    Location
    Barcelona
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Unhappy Sorting an array without using the method sort()

    Hi guys,

    I'm a beginner in Java. I need to sort a set of grades from students and print them sorted together with the index they occupy in the input vector. I've done the following:

     
    package edu.uoc.pac1;
     
    public class PAC1Ex3 {
     
    public static void sortAverageGradesAndShowIndices(double[] averageNotes) {
           double doubleNotes, aux;
            for (int i=0; i < averageNotes.length -1; i++){
                for (int j=0; j < averageNotes.length -1; j++){
                    // If actual number is higher than next one
                    if(averageNotes[j] > averageNotes[j+1]){
                        // Swapping 
                        aux = averageNotes[j];
                        averageNotes[j] = averageNotes[j+1];
                        averageNotes[j+1]=aux;
                    }
                }
            }
            // Print numbers sorted 
            for (int i=(averageNotes.length-1); i>=0;i--){
                System.out.println((averageNotes[i]));
            }
        }
    }

    I'm at the same time trying to test if it works with the following code:

     
    package edu.uoc.pac1;
     
    class PAC1Ex3Test {
     
    @Test
    @Order(4)
    void testSortAverageNotesAndShowIndices() {
     
            ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
            System.setOut(new PrintStream(outputStreamCaptor));
            PAC1Ex3.sortAverageGradesAndShowIndices(new double[] {4.2, 8.1, 9.4, 6.1, 4.7, 6.4, 6.0, 7.7});
            assertEquals("9.4 (2)"+System.lineSeparator()
                    + "8.1 (1)"+System.lineSeparator()
                    + "7.7 (7)"+System.lineSeparator()
                    + "6.4 (5)"+System.lineSeparator()
                    + "6.1 (3)"+System.lineSeparator()
                    + "6.0 (6)"+System.lineSeparator()
                    + "4.7 (4)"+System.lineSeparator()
                    + "4.2 (0)", outputStreamCaptor.toString().trim());
     
            outputStreamCaptor = new ByteArrayOutputStream();
            System.setOut(new PrintStream(outputStreamCaptor));
            PAC1Ex3.sortAverageGradesAndShowIndices(new double[] {6.6, 7.9, 8.9, 9.6, 7.3, 6.5, 4.0});
            assertEquals("9.6 (3)"+System.lineSeparator()
                    + "8.9 (2)"+System.lineSeparator()
                    + "7.9 (1)"+System.lineSeparator()
                    + "7.3 (4)"+System.lineSeparator()
                    + "6.6 (0)"+System.lineSeparator()
                    + "6.5 (5)"+System.lineSeparator()
                    + "4.0 (6)", outputStreamCaptor.toString().trim());
     
     
            outputStreamCaptor = new ByteArrayOutputStream();
            System.setOut(new PrintStream(outputStreamCaptor));
            PAC1Ex3.sortAverageGradesAndShowIndices(new double[] {7.0, 7.5, 8.0, 8.5, 9.0});
            assertEquals("9.0 (4)"+System.lineSeparator()
                    + "8.5 (3)"+System.lineSeparator()
                    + "8.0 (2)"+System.lineSeparator()
                    + "7.5 (1)"+System.lineSeparator()
                    + "7.0 (0)", outputStreamCaptor.toString().trim());
     
     
        }
    }

    However, my actual output is the following one:

    9.4
    8.1
    7.7
    6.4
    6.1
    6.0
    4.7
    4.2

    I'm missing the original position.

     
    org.opentest4j.AssertionFailedError: 
    <Click to see difference>
     
     
    	at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
    	at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
    	at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
    	at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
    	at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
    	at edu.uoc.pac1.PAC1Ex3Test.testSortAverageNotesAndShowIndices(PAC1Ex3Test.java:106)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    	at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    	at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    	at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    	at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    	at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
     
     
    Process finished with exit code -1
    Last edited by Panri93; October 2nd, 2021 at 12:55 PM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting an array without using the method sort()

    I'm getting AssertionFailedError.
    Where is that error message from? Can you copy the full contents of the console from when the code is executed and paste it here?

    How can a tester compile and execute the code? It is not complete; the posted code can not be compiled. It needs import statements, a class definition and a main method.


    Can you print out the results from the sort and compare it against the desired output to see what is wrong?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Oct 2021
    Location
    Barcelona
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Sorting an array without using the method sort()

    --- Update ---

    [/COLOR]
    Quote Originally Posted by Norm View Post
    Where is that error message from? Can you copy the full contents of the console from when the code is executed and paste it here?

    How can a tester compile and execute the code? It is not complete; the posted code can not be compiled. It needs import statements, a class definition and a main method.


    Can you print out the results from the sort and compare it against the desired output to see what is wrong?
    I've added what you asked for, please, let me know if you need anything else. For further clarification, the first test is passing the following vector of grades to be sorted: {4.2, 8.1, 9.4, 6.1, 4.7, 6.4, 6.0, 7.7}. The output to be successful should be something like:
    "9.4 (2)"
    "8.1 (1)"
    "7.7 (7)"
    "6.4 (5)"
    "6.1 (3)"
    "6.0 (6)"
    "4.7 (4)"
    "4.2 (0)"

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting an array without using the method sort()

    Have you printed out the results of the sortAverageGradesAndShowIndices method?
    Does the contents of that print out look ok?

    Add a print statement at the end of the method that prints out the contents of the array:
    System.out.println("an ID "+ java.util.Arrays.toString(theArrayName)); //<<  change theArrayName to the correct name
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Oct 2021
    Location
    Barcelona
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Sorting an array without using the method sort()

    Quote Originally Posted by Norm View Post
    Have you printed out the results of the sortAverageGradesAndShowIndices method?
    Does the contents of that print out look ok?

    Add a print statement at the end of the method that prints out the contents of the array:
    System.out.println("an ID "+ java.util.Arrays.toString(theArrayName)); //<<  change theArrayName to the correct name
    I'm getting the following:

    an ID[4.2, 9.4, 6.1, 4.7, 6.4, 6.0, 7.7, 8.1]

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting an array without using the method sort()

    I'm getting the following:
    Ok, does that look like the correct results? It does not look like it is sorted.
    If you don't understand my answer, don't ignore it, ask a question.

  7. The Following User Says Thank You to Norm For This Useful Post:

    Panri93 (October 2nd, 2021)

  8. #7
    Junior Member
    Join Date
    Oct 2021
    Location
    Barcelona
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Sorting an array without using the method sort()

    Yep... it seems that I'll need to work again on the code...

    --- Update ---

    Quote Originally Posted by Norm View Post
    Ok, does that look like the correct results? It does not look like it is sorted.
    I've modified the post and now I'm getting the desired result but I'm missing the position of the numbers from the source vector.

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting an array without using the method sort()

    I'm missing the position of the numbers from the source vector.
    So, you need to make some more changes to the code.
    Can you use a custom class to hold the item's value and its initial position in the array?
    If you don't understand my answer, don't ignore it, ask a question.

  10. #9
    Junior Member
    Join Date
    Oct 2021
    Location
    Barcelona
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Sorting an array without using the method sort()

    Quote Originally Posted by Norm View Post
    So, you need to make some more changes to the code.
    Can you use a custom class to hold the item's value and its initial position in the array?
    I didn't manage to do it. I don't see how!

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sorting an array without using the method sort()

    Create a class to hold the double number and the int initial index. Create a new array.
    For each double number in the original array, create an instance of the class with its double value and its int index number.
    Save that instance in the new array.
    Sort the objects in the new array based on the double value in the instance. Moving the instance around will always keep the double value paired with its int value.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. [SOLVED] Which sort method to use for a String Array to output the index?
    By DANGEROUSSCION in forum Algorithms & Recursion
    Replies: 11
    Last Post: December 8th, 2012, 10:25 PM
  2. Replies: 2
    Last Post: November 11th, 2012, 10:44 PM
  3. How to call a C sort function to sort a Java Array.
    By Dwere13 in forum Java Native Interface
    Replies: 22
    Last Post: July 12th, 2012, 04:44 PM
  4. How do I sort strings without using the sort method?
    By mjballa in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 4th, 2011, 03:27 PM
  5. Merge sort not sorting at all despite copying it exact from book.
    By javapenguin in forum Other Programming Languages
    Replies: 1
    Last Post: November 1st, 2011, 04:31 PM

Tags for this Thread