Asking anybody who knows Java to review this code (Sorting problem)

Hi, I know this forum doesn’t really focus on Java, but If I were to ask this on stack overflow I have a sense it would’ve been downvoted into oblivion. So I turn here.

I’m trying to write a basic sorting algo but I cant get it working. I want to swap the value of 101 into the first place of 104. So sort from Lowest to Highest. Can someone review this and tell me where I went wrong/ what I forgot/ how to fix it? Also trying to avoid built in methods as I want to practice with algorithm’s.

import java.util.Arrays;

public class sortString {
    public static void main (String[]args)
    {
        String word = "hello"; // initizlize word

        char array[] = word.toCharArray(); // create array of characters with length of word so 5
        int values[] = new int[array.length];
        
        for(int index = 0; index < array.length; ++index)
        {
            values[index] = array[index]; // gives all the chars numerical values
            int lowestValue = values[0]; // first index in array value is 104
            
            for(int j = 1; j < values.length; ++j)
            {
                if(values[j] < lowestValue) // if value[1] < value[0]
                {
                    lowestValue = values[j]; // the value[0] = the value at value[1]
                    values[j] = lowestValue;

                    System.out.println(lowestValue);
                }
            }

        }

        // assign that value to beginning of array
        // if values[1] < values[0] switch them

        System.out.println(Arrays.toString(values) + "\n");

I suspect that this isn’t doing what you think it’s doing. This means that for each iteration of the loop, only the first index items in values will contain nonzero values. From what you’re doing, I assume that you want to have completely copied the array before starting the loop.

If the goal is to put the smallest number first, then this will never do that. It’s putting lowestValue in values[j], not values[0]. Because the loop starts at values[1] you will never change the first number.
If the goal is to fully sort your array, you need to look more carefully at this logic:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.