w13 Cpe121

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

C P E 1 2 1 | | S O R T I N G | | P a g e |1

Bubble Sort
We can create a java program to sort array elements using bubble sort. In bubble sort algorithm, array is traversed from first
element to last element. Here, current element is compared with the next element. If current element is greater than the next
element, it is swapped.

Bubble Sort is the simplest sorting algorithm that works


by repeatedly swapping the adjacent elements if they are
in wrong order.

Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass
without any swap to know it is sorted.

Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
C P E 1 2 1 | | S O R T I N G | | P a g e |2

LM13-PROGRAM01 LM13-PROGRAM01-OUTPUT
public class Sort {
static void bubbleSort(int[] arr)
{ int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(arr[j-1] > arr[j])
{//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp; }
}
}
}
public static void main(String[] args) {
int arr[] ={3,60,35,2,45,320,5};

System.out.println("Array Before Bubble Sort");


for(int i=0; i < arr.length; i++)
{System.out.print(arr[i] + " ");}

System.out.println();

bubbleSort(arr);//sorting array elements using bubble sort

System.out.println("Array After Bubble Sort");


for(int i=0; i < arr.length; i++)
{System.out.print(arr[i] + " ");}
}
}
C P E 1 2 1 | | S O R T I N G | | P a g e |3

LM13-PROGRAM02 LM13-PROGRAM02-OUTPUT
import java.util.Scanner;

public class Sort {


public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);

System.out.println("Enter the number of integers to sort:");


num = input.nextInt();

int array[] = new int[num];

System.out.println("Enter " + num + " integers: ");

for (i = 0; i < num; i++)


array[i] = input.nextInt();

for (i = 0; i < ( num - 1 ); i++)


{for (j = 0; j < num - i - 1; j++)
{if (array[j] > array[j+1])
{temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;}
}
}
System.out.println("Sorted list of integers:");
for (i = 0; i < num; i++)
System.out.println(array[i]);
}
}
C P E 1 2 1 | | S O R T I N G | | P a g e |4

LM13-PROGRAM03

import java.util.Scanner;
import java.util.Arrays;
// driver code
public class Sort { public static void main(String args[]) {
Scanner input = new Scanner(System.in); // create an array
// method to perform bubble sort int[] data = { -2, 45, 0, 11, -9 };
void bubbleSort(int array[]) { // create an object of Main class
int size = array.length; Sort Sort = new Sort();
// call the method bubbleSort using object bs
// for ascending or descending sort
// pass the array as the method argument
System.out.println("Number to sort: -2, 45, 0, 11, -9"); Sort.bubbleSort(data);
System.out.println("Sorting Order:"); System.out.println("Sorted Array in Ascending Order:");
System.out.println("1 for Ascending \n2 for Descending"); // call toString() of Arrays class
System.out.println("Choose a Sorting Order:[1,2]"); // to convert data into the string
int sortOrder = input.nextInt(); System.out.println(Arrays.toString(data));
// run loops two times }
// first loop access each element of the array }
for (int i = 0; i < size - 1; i++)
// second loop performs the comparison in each iteration
for (int j = 0; j < size - i - 1; j++)
// sort the array in ascending order
if (sortOrder == 1) {
if (array[j] > array[j + 1]) {
// swap if left element is greater than right
int temp = array[j];
array[j] = array[j + 1];

// compares the adjacent element


array[j + 1] = temp;}
}
// sort the array in descending order
else {
// compares the adjacent element
if (array[j] < array[j + 1]) {
// swap if left element is smaller than right
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp; }
} }
C P E 1 2 1 | | S O R T I N G | | P a g e |5

SELECTION SORTING
Selection sort finds the smallest element in the array and place it on the first place on the list, then it finds the second smallest
element in the array and place it on the second place. This process continues until all the elements are moved to their correct
ordering.

How does selection sort work?


The selection sort algorithm works in a very simple way. It maintains two sub-array for the given array.
• The sub-array is already sorted.
• And the second sub-array is unsorted.
With every iteration of selection sort, an element is picked from the unsorted sub-array and moved to the sorted sub-array.

LM13-PROGRAM04 LM13-PROGRAM04-OUTPUT
public class SelectionSortExample {
public static void main(String a[]){
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1)
{System.out.print(i+" ");}
System.out.println();
selectionSort(arr1);//sorting array using selection sort
System.out.println("After Selection Sort");
for(int i:arr1)
{System.out.print(i+" "); }
}
public static void selectionSort(int[] arr)
{ for (int i = 0; i < arr.length - 1; i++)
{ int index = i;
for (int j = i + 1; j < arr.length; j++)
{ if (arr[j] < arr[index]){
index = j;}//searching for lowest index }
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber; }
} } }
C P E 1 2 1 | | S O R T I N G | | P a g e |6

QUICK LOOK ON for-each Loop

Sytnax:
The syntax of the Java for-each loop is:

for(dataType item : array)


{... }
Here:
array - an array or a collection
item - each item of array/collection is assigned to this variable
dataType - the data type of the array/collection

LM13-PROGRAM05: Print Array Elements LM13-PROGRAM05-OUTPUT


// print array elements

public class ForEachLoop {


public static void main(String[] args) {

// create an array
int[] numbers = {3, 9, 5, -5};

// for each loop


for (int number: numbers)
{ System.out.println(number); }
}
}
C P E 1 2 1 | | S O R T I N G | | P a g e |7

CHARACTERS AND STRINGS

LM11-PROGRAM01. Program that inserts a double quote (“ ”) in the println statement.

public class Test {


public static void main(String args[]) {
System.out.println("She said \"Hello!\" to me.");
}
}
LM11-PROGRAM01-OUTPUT

Character Methods
Following is the list of the important instance methods that all the subclasses of the Character class implement −

Sr.No. Method & Description


1 isLetter()
Determines whether the specified char value is a letter.
2 isDigit()
Determines whether the specified char value is a digit.
3 isWhitespace()
Determines whether the specified char value is white space.
4 isUpperCase()
Determines whether the specified char value is uppercase.
5 isLowerCase()
Determines whether the specified char value is lowercase.
6 toUpperCase()
Returns the uppercase form of the specified char value.
7 toLowerCase()
Returns the lowercase form of the specified char value.
8 toString()
Returns a String object representing the specified character value that is, a one-character string

Strings

String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable object
which means it is constant and can cannot be changed once it has been created. In this module we will learn about
String class and String methods in detail along with many other Java Strings. In Java programming language, strings
are treated as objects. The Java platform provides the String class to create and manipulate strings.

Creating a String
There are two ways to create a String in Java
1. String literal
2. Using new keyword
Object-Oriented Programming Page 8 of 11
Sorting
String literal
In java, Strings can be created like this: Assigning a String literal to a String instance:
String str1 = "Welcome";
String str2 = "Welcome";

Using New Keyword


As we saw above that when we tried to assign the same string object to two different literals, compiler only created
one object and made both of the literals to point the same object. To overcome that approach we can create strings
like this:

String str1 = new String("Welcome");


String str2 = new String("Welcome");

In this case compiler would create two different object in memory having the same string.

LM011-Program02 LM011-Program02-OUTPUT
public class {
public static void main(String args[]){
//creating a string by java string literal
String str = "—BSCpE--";
char arrch[]={'h','e','l','l','o'};
//converting char array arrch[] to string str2
String str2 = new String(arrch);

//creating another java string str3 by using new keyword


String str3 = new String("Java String Example");

//Displaying all the three strings


System.out.println(str);
System.out.println(str2);
System.out.println(str3); }
}

LM011-Program03 LM011-Program03-OUTPUT
public class StringDemo {

public static void main(String args[]) {


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
Object-Oriented Programming Page 9 of 11
Sorting

LM11-PROGRAM04 LM11-PROGRAM04-OUTPUT
public class CharString {

public static void main(String[] args) {


char ch = 'c';
String st = Character.toString(ch);
// Alternatively
// st = String.valueOf(ch);

System.out.println("The string is: " + st);


}
}

String Length
Methods used to obtain information about an object are known as accessor methods. One accessor method that
you can use with strings is the length() method, which returns the number of characters contained in the string object.

The following program is an example of length(), method String class.

LM11-PROGRAM05 LM11-PROGRAM05-OUTPUT
public class StringDemo {

public static void main(String args[]) {


String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len ); }
}

Converting String to Char


We can convert a String to char using charAt() method of String class.

LM11-PROGRAM07 LM11-PROGRAM07-OUTPUT
class StringToCharDemo {
public static void main(String args[]) {
// Using charAt() method
String str = "Hello";
for(int i=0; i<str.length();i++){
char ch = str.charAt(i);
System.out.println("Character at "+i+" Position: "+ch); }
}
}
Object-Oriented Programming Page 10 of 11
Sorting

Convert char array to String


If you have a char array instead of just a char, we can easily convert it to String using String methods as follows:

LM11-PROGRAM08 LM11-PROGRAM08-OUTPUT

public class CharString {

public static void main(String[] args) {


char[] ch = {'a', 'e', 'i', 'o', 'u'};

String st = String.valueOf(ch);
String st2 = new String(ch);

System.out.println(st);
System.out.println(st2);
}
}

LM11-PROGRAM09. Program to change upper/lower case. LM11-PROGRAM09-OUTPUT

public class StringDemo {

public static void main(String args[]) {


String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase()); }
}

String Concatenation

The + operator can be used between strings to combine them. This is called concatenation:

LM11-PROGRAM010 LM11-PROGRAM010
public class StringDemo {

public static void main(String args[]) {


String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName)); }
}
Object-Oriented Programming Page 11 of 11
Sorting

LM11-PROGRAM011 LM11-PROGRAM011-OUTPUT

public class StringMethod {


public static void main(String[] args) {

// create string using the new keyword


String example = new String("Hello! World");
// returns the substring World
System.out.println("Using the subString(): " + example.substring(7));
// converts the string to lowercase
System.out.println("Using the toLowerCase(): " + example.toLowerCase());
// converts the string to uppercase
System.out.println("Using the toUpperCase(): " + example.toUpperCase());
// replaces the character '!' with 'o'
System.out.println("Using the replace(): " + example.replace('!', 'o')); }
}

LM11-PROGRAM012 LM11-PROGRAM012-OUTPUT
public class StringMethod {

public static void main(String[] args) {

String str = "S T R E S S E D";


StringBuffer sb = new StringBuffer(str);
sb.reverse();
System.out.println(sb); }
}

You might also like