(JAVA CODE)Please provide a 1d array of size 10 filled
with random integers between 0 and 100. Please then sort this array
using the insertion sorting algorithm.
Pseudocode:
Method will take an array of integers
A loop for the current element
Another loop (nested) to check the next item is
lower/smaller
If true, swapping operation
Else, move to the next iteration
public static int [ ] insertionSort (int [ ] myArray)
{
int currentElement; j;
for (int i = 1; i < myArray.length; i++)
{
currentElement = myArray [ i ];
j = i - 1;
while ( j >= 0 && myArray [ i ] >
currentElement) {
myArray [ j+1 ] = myArray [ j ];
j = j - 1;
}
myArray [ j+1] = currentElement;
}
return myArray;
}
int [ ] numbers = { 5, 2, 9, 1,3};
2 5 9 1
2 5 1 9
2 1 5 9
1 2 5 9
Task-2: Please write the pseudocode and the full code
for the bubble sorting algorithm and show it with an
example.
Pseudocode:
Function with an input 1-d array
Declare i and j and temp
A loop index=1 till the end and boolean pass
variable
Inside loop: if the current item is bigger than the next
one
Then we swap them (otherwise no swap
operation)
If there is no swap operation in a pass then we stop the
process
Then we go to the next index…
public static int [ ] bubbleSort (int[ ] array)
{
int i, j, temp = 0;
boolean doesPass = true;
for (i = 1; i < array.length && doesPass;
i++) {
for (j = 0; j < array.length - i; j++) {
doesPass = false;
if (array[ j ] > array[ j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
doesPass = true;
}
}
}
return array;
}
int [ ] numbers = { 5, 2, 9, 1, 3};
2 5 9 1
2 5 1 9
2 1 5 9
1 2 5 9
-
(JAVA CODE)Please provide a 1d array of size 10 filled with random integers between 0 and 100. Please then sort this arr
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
(JAVA CODE)Please provide a 1d array of size 10 filled with random integers between 0 and 100. Please then sort this arr
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!