Valencia, Gian Kurt D. CEIT-37-302-A: Code

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Valencia, Gian Kurt D.

CEIT-37-302-A

Sorting Numbers Ascending Order

Code:
import java.util.Arrays;
public class Sorting
{
public static void main(String[]args)
{
int Sort[]={10,5,8,9,24,50,1,17};
Arrays.sort(Sort);

for(int j=0; j<Sort.length; j++)


{
System.out.println(Sort[j]);
}
}
}
Output:

Sorting Numbers Descending Order

Code:
import java.util.Scanner;
public class SortingDescending
{
public static void main(String[] args)
{
int n, bbq;
Scanner scan = new Scanner(System.in);
System.out.print("Number of Elements: ");
n = scan.nextInt();
int a[] = new int[n];
System.out.println("Input Elements: ");
for (int i = 0; i < n; i++)
{
a[i] = scan.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] < a[j])
{
bbq = a[i];
a[i] = a[j];
a[j] = bbq;
}
}
}
System.out.print("Descending Order: ");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}

Output:
Sorting Methods

1. Bubble Sort
= works by swapping adjacent elements if they're not in the desired order. This process
repeats from the beginning of the array until all elements are in order
2. Insertion Sort
= dividing the array into the sorted and unsorted subarrays
3. Selection Sort
= Selection Sort also divides the array into a sorted and unsorted subarray. Though, this time,
the sorted subarray is formed by inserting the minimum element of the unsorted subarray at
the end of the sorted array, by swapping

1. public static void main(String a[]){


2. int[] arr1 = {9,14,3,2,43,11,58,22};
3. System.out.println("Before Selection Sort");
4. for(int i:arr1){
5. System.out.print(i+" ");
6. }
7. System.out.println();
8.
9. selectionSort(arr1);//sorting array using selection sort
10.
11. System.out.println("After Selection Sort");
12. for(int i:arr1){
13. System.out.print(i+" ");
14. }
15. }
16. }
4. Merge Sort
=Merge Sort uses recursion to solve the problem of sorting more efficiently than algorithms
previously presented, and in particular it uses a divide and conquer approach.
5. Heap Sort
= Heap sort processes the elements by creating the min heap or max heap using the elements
of the given array. Min heap or max heap represents the ordering of the array in which root
element represents the minimum or maximum element of the array. At each step, the root
element of the heap gets deleted and stored into the sorted array and the heap will again be
heapified.
6. Quick Sort
= Quicksort is another Divide and Conquer algorithm. It picks one element of an array as the
pivot and sorts all of the other elements around it, for example smaller elements to the left, and
larger to the right.

You might also like