0% found this document useful (0 votes)
2 views

Sort

The document contains a Java class named 'Sort' that implements three sorting algorithms: bubble sort for ascending order, bubble sort for descending order, and selection sort for strings. Each sorting method modifies the input array and returns the sorted result. The bubble sort methods use nested loops to compare and swap elements, while the selection sort method finds the smallest element and places it in the correct position iteratively.

Uploaded by

panav.golyan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Sort

The document contains a Java class named 'Sort' that implements three sorting algorithms: bubble sort for ascending order, bubble sort for descending order, and selection sort for strings. Each sorting method modifies the input array and returns the sorted result. The bubble sort methods use nested loops to compare and swap elements, while the selection sort method finds the smallest element and places it in the correct position iteratively.

Uploaded by

panav.golyan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

File: Untitled Document 1 Page 1 of 2

/**
* Write a description of class Sort here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Sort
{
//This function sorts an array
int[] bubbleSort (int[] nos)// Works by checking the first two elements sorting them ,
then moving on to the next two.
{

int f , s;

for(int k = 0;k <= nos.length;k+=1)


{
for( int i = 0;i < nos.length-1;i+=1)
{
f = nos[i];
s = nos[i+1];
if (f > s)
{
nos[i] = s;
nos[i+1] = f;
}
}
}
return nos;
}

//This sorts an array in descending order


int[] bubbleDescending (int [] nos)
{
int i = 0;
int f , s;
int k = 0;
while(k <= nos.length)
{
i=0;//important to add this as the value should reset after the loop
while( i < nos.length-1)
{
f = nos[i];
s = nos[i+1];
if (f < s)//We have to reverse the sign for descending
{
nos[i] = s;
nos[i+1] = f;
}
i++;
}
k++;
}
return nos;
}

//This function sorts an array


String [] selectionSort (String[] a)
{
int k = 0;
String s , s2;
int n = 0;
char c , c2;
while(k < a.length - 1)
{
File: Untitled Document 1 Page 2 of 2

n = k + 1;
while(n < a.length)
{
s = a[k];
s2 = a[n];
if (s.compareToIgnoreCase(s2) > 0)
{
a[k] = s2;
a[n] = s;
}
n++;//only n should increase as the first element will become the shortest
}
k++;
}
return a;
}
}

You might also like