Manually sorting an array in ascending order

I have a homework to sort an array in ascending order. Obviously, this must be done manually without using any function sort().

I decided to do this, I will need two cycles for: the first will go through the existing array and create a temporary value with the value and index of the array. The second cycle will compare time values ​​with existing values ​​and sort them. I try to write code all the time, but I just can't figure out how to do it right. Here is the last method I came up with:

public int[] sortArray (int[] inArray)
{
    //Construct the array we're using here
    int[] newArray = inArray;

    for(int x = 0; x < a.length; x++) //a.length = # of indices in the array
    {
        int tempValue = a[x];
        int tempIndex = x;

        for(int y = 0; y < a.length; y++)
        {
            if(tempValue < a[y])
            {
                newArray[x] = tempValue;
            }
        }
    }

    return newArray;
}

I am sure that this is wrong, but if someone can push me in the right direction, it will be very grateful!

+5
source
7

. y x+1, 0. . , - ; , Arrays.copy, int[] newArray = inArray; , . , if a[x] a[y], tempValue :

if(newArray[x] < newArray [y]) {
    int tempValue = newArray[y];
    newArray[y] = newArray[x];
    newArray[x] = tempValue;
}
+5

, , , . .

: .

Bubble sort , ( , ).

Quicksort .

+1

, , Bubble sort - , . , - ( Timsort Python, ). , , , O (n 2).

, , :

, .

+1
source
int minval = input[0];
int temp=0;


for(int i = 0; i< input.length; i++)
{ 
    for(int j = 0; j< input.length-1; j++)
    {
        if(input[j+1]<input[j])
        {
            temp=input[j+1];
            input[j+1]=input[j];
            input[j]=temp;  
        }
    }
}
0
source
int arr[] = new int[]{10, 20, 5, 6, 30, 1, 2};
    boolean bool = true;
    int t = 0;
    while (bool) {
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                int c = arr[i];

                arr[i] = arr[i + 1];
                arr[i + 1] = c;
                t++;
            }
        }
        if (t == 0) {
            bool = false;
        }
        t = 0;
    }

    for (int y : arr) {
        System.out.println(y);
    }
0
source
int[] number = { 1,2,1,3,5,4 };
    int temp;
     for (int i = 0; i < number.length; i++)
        {
            for (int j = i + 1; j < number.length; j++)
            {
                if (number[i] > number[j])
                {
                    temp =  number[i];
                    number[i] = number[j];
                    number[j] = temp;
                }
            }
        }

        for (int i = 0; i <number.length; ++i)
            System.out.println(number[i]);
    }
-1
source

All Articles