How to implement a descending selection sort - java

The method I have to create should take as parameter an array of integers and return the integer array with its contents sorted in descending order — largest to smallest.
Note - no libraries should be used in your implementation for this method.
I've attempted to use a regular selection sort and using a swap at the end but syntax errors just occurred:
public static int[] reverseSelectionSort(int[] arrayToBeSorted) {
// implementation of Task 3 goes here
for(int i = 0; i < arrayToBeSorted.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < arrayToBeSorted.length - i; j++){
if(arrayToBeSorted[j] < arrayToBeSorted[minPosition]){
minPosition = j;
}
if(arrayToBeSorted[j] > arrayToBeSorted[maxPosition]){
maxPosition = j;
}
}
swap(arrayToBeSorted,minPosition,maxPosition);
swap(arrayToBeSorted,maxPosition,i);
swap(arrayToBeSorted,minPosition,arrayToBeSorted.length-i-1);
}
return arrayToBeSorted; // change this to return the sorted array
}
public static void main(String[] args) {
int[] array2 = {3, 6, 8, 3, 5, 7, 1};
int[] sorted = reverseSelectionSort(array2);
System.out.print("task: [");
for (int i = 0; i < sorted.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(sorted[i]);
}
System.out.println("]");
}
If you call the method on the array [3, 6, 8,
3, 5, 7, 1], then the method should return the array [8, 7, 6, 5, 3, 3, 1].

Once you add the implementation of swap to your code (and put it all inside a class), it produces exactly the output you wanted it to. Maybe you thought swap was a java uitl, which it is for Collections, but an array is not a Collection.
So very little has changed in the below:
public class soSelect{ //embed in class, added
public static int[] reverseSelectionSort(int[] arrayToBeSorted) {
// implementation of Task 3 goes here
for(int i = 0; i < arrayToBeSorted.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < arrayToBeSorted.length - i; j++){
if(arrayToBeSorted[j] < arrayToBeSorted[minPosition]){
minPosition = j;
}
if(arrayToBeSorted[j] > arrayToBeSorted[maxPosition]){
maxPosition = j;
}
}
swap(arrayToBeSorted,minPosition,maxPosition);
swap(arrayToBeSorted,maxPosition,i);
swap(arrayToBeSorted,minPosition,arrayToBeSorted.length-i-1);
}
return arrayToBeSorted; // change this to return the sorted array
}
public static void swap(int[] a, int i, int j){ //had to implement it
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
int[] array2 = {3, 6, 8, 3, 5, 7, 1};
int[] sorted = reverseSelectionSort(array2);
System.out.print("task: [");
for (int i = 0; i < sorted.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(sorted[i]);
}
System.out.println("]");
}
}//added outer brace
I ran it in java doodle and it printed:
task: [8, 7, 6, 5, 3, 3, 1]
I did not test beyond that, but this should at least get you unstuck, or, at best, finished. For sure you could compare with the implementation to which the above comment points you.

Related

ArrayList Bubblesort with strings

The sorting is not working, it doesn't sort the names by the alphabet, I wrote a bubble sort algorithm with int and it worked fine. Can you help me? Is something wrong with the compareTo() method?
public ArrayList<FootballPlayer> sortByNames(ArrayList<FootballPlayer> pList)
{
FootballPlayer z;
for(int i=0; i<pList.size(); i++)
{
for(int j=0; j<pList.size()-i-1;j++)
{
if((pList.get(i).getName()).compareTo(pList.get(j+1).getName())>0)
{
z = pList.get(j);
pList.set(j, pList.get(j+1));
pList.set(j+1,z);
}
}
}
for(int i=0; i<pList.size(); i++)
{
System.out.print(pList.get(i).getName()+";");
System.out.println("");
}
return pList;
}
Your implementation is not BubbleSort! Check Bubble sort or event a bit more advanced Cocktail shaker sort.
public static void bubbleSort(List<String> pList) {
boolean done = false;
for (int i = pList.size(); !done; i--) {
done = true;
for (int j = 0; j + 1 < i; j++) {
if (pList.get(j).compareTo(pList.get(j + 1)) <= 0)
continue;
done = false;
String tmp = pList.get(j);
pList.set(j, pList.get(j + 1));
pList.set(j + 1, tmp);
}
}
}
Output:
List<String> pList = new ArrayList<>();
for (int i = 0; i < 10; i++)
pList.add(String.valueOf(i));
Collections.shuffle(pList);
System.out.println(pList); // [0, 6, 7, 9, 5, 8, 4, 1, 3, 2]
bubbleSort(pList);
System.out.println(pList); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Make a new array with common elements in two arrays

I have to create a method, that returns an array with common elements from two different arrays. I am aware there are lots of questions about this, but mine is a little bit different from those as I have to create a new array.
I've tried to first count how many common elements there are from two arrays, and then create an array with size the number of that.
After, I tried to set the new array to the common elements using a for loop.
public static int [] commonElements(int []a, int [] b){
int count=0;
for(int i=0;i<a.length;i++) {
for(int j=0;j<b.length;j++) {
if(a[i] == b[j]) {
count++;
}
}
}
int []array= new int[count];
for(int i=0;i<a.length;i++) {
for(int j=0;j<b.length;j++) {
if(a[i] == b[j]) {
for (int k=0; k<count; k++){
array[k]=a[i];
}
}
}
}
return array;
}
This returns four -1's, so it doesn't work.
I am also required not to use arraylist, so I have no idea how to make this code complete.
The expected value with
// checking common elements
System.out.println ("\nLooking for common elements in the arrays ");
int [] arr3= {56, -21, -5, 7, 10, 21, 2, -1};
int [] arr4= {-1, -56, 5, 21, 3 , 7, 4, -6, 2, 90};
int [] result4 = commonElements(arr3, arr4);
System.out.println (Arrays.toString(arr3));
System.out.println (Arrays.toString(arr4));
System.out.print ("\nCommon elements array: ");
System.out.println (Arrays.toString(result4));
in the main is
Looking for common elements in the arrays
[56, -21, -5, 7, 10, 21, 2, -1]
[-1, -56, 5, 21, 3, 7, 4, -6, 2, 90]
Common elements array: [7, 21, 2, -1]
Any help would be greatly appreciated!
You might want to use a list to store the intermediate intersecting values, and then convert to an array at the end of the method:
public static int[] commonElements(int[] a, int[] b) {
List<Integer> common = new ArrayList<>();
for (int i=0; i < a.length; i++) {
for(int j=0; j < b.length; j++) {
if (a[i] == b[j]) {
common.add(a[i]);
}
}
}
int[] array = common.stream().mapToInt(Integer::intValue).toArray();
return array;
}
If you don't want to record duplicates, then replace common with Set<Integer>.
First, instead of int []array= new array[count]; you need new int[count]; - second, instead of a third inner loop when populating your output keep a position index and increment it when you encounter a duplicate. Like,
public static int[] commonElements(int[] a, int[] b) {
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
count++;
}
}
}
int[] array = new int[count];
int p = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
array[p] = a[i];
p++;
}
}
}
return array;
}
Alternatively, if using Java 8+, the above can be simplified by filtering on an IntStream of the two arrays. Like,
return Arrays.stream(a).filter(i -> Arrays.stream(b).anyMatch(x -> x == i))
.toArray();

Inserting an integer into a sorted array

I'm trying to write a method that takes a sorted array and an integer, creates a new array that is 1 size larger, and inserts the new integer and keeps it sorted.
I've tried a few different implementations and had them to work - but for this specific one, I can't grasp where it's going wrong.
int[] array1 = new int[]{1, 2, 3, 4, 6, 7, 8};
int[] printArray = insert(array1, 5);
are the arrays, and the method is
public static int[] insert(int[] a, int k) {
int[] s = new int[a.length + 1];
for(int i = 0; i < a.length; i++) {
if(k < s[i]) {
s[i] = k;
for(int j = i + 1; j < s.length; j++) {
s[j] = a[i];
i++;
}
return s;
} else {
s[i] = a[i];
}
}
return s;
}
This method prints out 1, 2, 3, 4, 6, 7, 8, 0, instead of 1, 2, 3, 4, 5, 6, 7, 8.
Change
if(k < s[i]) {
to
if(k < a[i]) {
in line 4.
Actually in the following line you are creating an array with all elements zero:
int[] s = new int[a.length + 1];
s[0] to s[7] will be 0.
Your loop counter i runs from 0 to a.length but the point to note is all the elements of array s will be zero. You are comparing k with s[i] which is zero and for that reason the shifting of arrays never happen (if block never executes).
You need to do two things to fix it.
Initialize element zero of s with the value of a[0].
Compare element with previous element to figure out position to insert.
The final code is:
public static int[] insert(int[] a, int k) {
int[] s = new int[a.length + 1];
s[0] = a[0];
for(int i = 1; i < a.length; i++) {
if(k < s[i-1]) {
s[i] = k;
for(int j = i + 1; j < s.length; j++) {
s[j] = a[i];
i++;
}
return s;
} else {
s[i] = a[i];
}
}
return s;
}
Now you will get:
[1, 2, 3, 4, 6, 5, 7, 8]
I would start by using Arrays.copyOf(int[], int) to create a new array that is one larger than the input. Then iterate that array until I reached the index that the new value belongs at. Then use System.arraycopy(Object,int,Object,int,int) to copy the values into the end of the array. That might look something like
public static int[] insert(int[] a, int k) {
int[] s = Arrays.copyOf(a, a.length + 1);
for (int i = 0; i < s.length; i++) {
if (a[i] < k) {
continue;
}
System.arraycopy(a, i, s, i + 1, s.length - i - 1);
s[i] = k;
break;
}
return s;
}
Which I tested with Arrays.toString(int[]) like
public static void main(String s[]) throws IOException {
int[] array1 = new int[] { 1, 2, 3, 4, 6, 7, 8 };
int[] printArray = insert(array1, 5);
System.out.println(Arrays.toString(printArray));
}
And I get the (expected)
[1, 2, 3, 4, 5, 6, 7, 8]

Java filling in an array

How would one go about filling in an array so that, for example, if you had the following array.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 3;
arr[2] = 7;
arr[3] = 2;
arr[4] = -4;
so it would look like
arr = {1, 3, 7, 2, -4};
and you would pass it into your method to get a result of
arr = {1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4};
so that you essentially are filling in the numeric gaps. I'd like to make this under the assumption that I don't know how long the array passed in is going to be to make it a more universal method.
my current method looks like such right now...
public static void fillArray(int[] numbers){
int length = numbers.length;
for(int i = 0; i < numbers.length - 1; i ++){
if(numbers[i] <= numbers[i + 1]){
length += numbers[i + 1] - numbers[i];
}else if(numbers[i + 1] < numbers[i]){
length += numbers[i + 1] - numbers[i];
}
}
}
I have length to determine the size of my new array. I think it should work but I'm always down for some input and advice.
Looks like homework, providing algorithm only:
Navigate through the elements of the current array.
Get the distance (absolute difference) between the elements in the array.
Summarize the distances.
Create a new array whose length would be the sum of the distances.
Fill the new array using the elements of the first array and filling the gaps.
Return the array.
Like Luiggi Mendoza said, looks like HW, so here's another algorithm:
insert the first element into a list of integers.
loop on the rest of the elements.
for each two array elements X[i-1], X[i], insert the missing integers to the list
after the loop - use guava to turn the List to array.
This works. just check for array size < 2 for safety.
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
Integer[] result = fillArray(arr);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
private static Integer[] fillArray(int[] arr) {
List<Integer> list = new ArrayList<Integer>();
list.add(arr[0]);
for (int i = 1; i < arr.length; i++) {
int prevItem = arr[i-1];
int gap = arr[i] - prevItem;
if(gap > 0){
fillGap(list, prevItem, gap, 1);
} else if(gap < 0){
fillGap(list, prevItem, gap, -1);
}
}
return list.toArray(new Integer[0]);
}
private static void fillGap(List<Integer> list, int start, int gap, int delta) {
int next = start+delta;
for (int j = 0; j < Math.abs(gap); j++) {
list.add(next);
next = next+delta;
}
}
Try
import java.util.ArrayList;
import java.util.List;
public class ArrayGap {
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
int high, low;
List<Integer> out = new ArrayList<Integer>();
for(int i=0; i<arr.length - 1; i++){
high = arr[i];
if(arr[i] < arr[i+1]){
for(int j=arr[i]; j<arr[i+1]; j++){
out.add(j);
}
} else {
for(int j=arr[i]; j>=arr[i+1]; j--){
out.add(j);
}
}
}
System.out.println(out);
}
}

Sort an array such a way that First half should be in ascending order Second half should be in descending order in java

I have searched a lot in google but I didnt get any kind of solution I could use. Suppose input of array is:
{3,1,2,4,9,8,7,6,5,10}
then output must be like this:
{1,2,3,4,5,10,9,8,7,6}
by using Basic Java .
Your array: {3,1,2,4,9,8,7,6,5,10}
Sort it in ascending order: {1,2,3,4,5,6,7,8,9,10}
Break this array into two half arrays: {1,2,3,4,5}{6,7,8,9,10}
Sort the second array in descending order or reverse it: {10, 9,8,7,6}
Add the second array to the first array & you get: {1,2,3,4,5,10,9,8,7,6}
This would be the minimal code which uses an array of primitive ints:
static final int[] xs = {3,1,2,4,9,8,7,6,5,10};
static void sortAndReverse() {
Arrays.sort(xs);
for (int i = xs.length/2; i < dest(i); i++) {
int tmp = xs[i]; xs[i] = xs[dest(i)]; xs[dest(i)] = tmp;
}
System.out.println(Arrays.toString(xs));
}
static int dest(int i) { return 3*xs.length/2-i-1; }
If you're not ashamed of using wrapper objects, then this is unbeatable:
final Integer[] xs = {3,1,2,4,9,8,7,6,5,10};
final List<Integer> list = Arrays.asList(xs);
Collections.sort(list);
Collections.reverse(list.subList(list.size()/2, list.size()));
System.out.println(Arrays.toString(xs));
Please find the below code
import java.util.Arrays;
public class fre {
public static void main(String[] args) {
int[] vals = { 3, 1, 2, 4, 9, 8, 7, 6, 5, 10 };
Arrays.sort(vals); // Sorts the basic first array
int[] vals2 = Arrays.copyOfRange(vals, vals.length / 2, vals.length); // Gets the las values of the arrays i.e. it devies the array in multiple same part and another array is created
// Below loop will reverse the second array
for (int i = 0; i < vals2.length / 2; i++) {
int temp = vals2[i];
vals2[i] = vals2[vals2.length - 1 - i];
vals2[vals2.length - 1 - i] = temp;
}
vals = Arrays.copyOfRange(vals, 0, vals.length / 2);
// Final array array1and2 will be created where we will append first array with second array
int[] array1and2 = new int[vals.length + vals2.length];
System.arraycopy(vals, 0, array1and2, 0, vals.length);
System.arraycopy(vals2, 0, array1and2, vals.length, vals2.length);
// Prints the final result array
System.out.println(Arrays.toString(array1and2));
}
}
Output
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
You can use the java features to do this too ... Use
public static <T> void sort(T[] a,
int fromIndex,
int toIndex,
Comparator<? super T> c)
But the elements need to be objects ... The comparator needs to be changed while sorting the first half and second half of the array.
Should be a bit simpler than manually reversing each item in the second half.
Integer [] array = { 3,1,2,4,9,8,7,6,5,10 };
Arrays.sort(array);
Arrays.sort(array, array.length/2, array.length, new Comparator<Integer>(){
#Override
public int compare(Integer o1, Integer o2)
{
return -o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(array));
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
IPSOS isn't it?
int m;
if(array.length%2==0)
m=array.length/2;
else
m=(array.length+1)/2;
for(int i=0; i<array.length; ++i){
if(i<m){
int min = i;
for(int j=i+1; j<m;++j){
if(array[min]>array[j]){
min=j;
}
int tem = array[i];
array[i]=array[min];
array[min]=tem;
}
}
else {
int max = i;
for(int k=i+1; k<array.length; ++k){
if(array[max]<array[k]){
max=k;
}
int te = array[i];
array[i]=array[max];
array[max]=te;
}
}
}
for(int i=0;i<array.length;++i){
System.out.print(array[i] + " ");
}
1. Sort the array input_Array[]
2. j = lenght(input_Array)-1
3. loop i = lenght(input_Array)/2 to j
swap(input_Array[i] , input_Array[j-i])
input: 3,1,2,4,9,8,7,6,5,10
output: 1 3 5 7 9 10 8 6 4 2 (uniform acceding and descending )
public class AscendingDecending {
public static void main(String[]args) {
int a[]= {2,3,2,5,7,5,6,3};
int i,j,temp;
//Traverse the element of array
System.out.println("Input:");
for(i=0; i<a.length; i++) {
System.out.print(" "+ a[i]);
}
//lets move for ascending function
System.out.println("");
System.out.println("Output:");
//Create a Swap Function for sorting
for(i=0; i<a.length; i++) {
for(j=i+1; j<a.length; j++) {
if(a[i]>a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
//For Descending
for(i=0; i<a.length; i++) {
for(int j=i+1; j<a.length; j++) {
if(a[i]<a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
System.out.println(" ");
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
}
}
I hope this piece of code will help:
static void printarray(int[] arr, int len)
{
Arrays.sort(arr);
for (int i = 0; i < len / 2; i++)
System.out.println(arr[i]);
for (int j = len - 1; j >= len / 2; j--)
System.out.println(arr[j]);
}

Categories

Resources