You are on page 1of 7

Useful Algorithms:

QuickSort Java Example:

Quicksort algorithm is one of the most used sorting algorithm, especially to sort large
lists/arrays. Quicksort is a divide and conquer algorithm, which means original array is divided
into two arrays, each of them is sorted individually and then sorted output is merged to
produce the sorted array. On the average, it has O(n log n) complexity, making quicksort
suitable for sorting big data volumes.
In more standard words, quicksort algorithm repeatedly divides an un-sorted section into a
lower order sub-section and a higher order sub-section by comparing to a pivot element. At the
end of recursion, we get sorted array. Please note that the quicksort can be implemented to
sort in-place. This means that the sorting takes place in the array and that no additional array
need to be created.
Quicksort algorithm
The basic idea of Quicksort algorithm can be described as these steps:
If the array contains only one element or zero elements then the array is sorted. If the array
contains more then one element then:
1. Select an element as a pivot element, generally from middle but not necessary.
2. Data elements are grouped into two parts: one with elements that are in lower order
than the pivot element, one with element that are in higher order than the pivot
element.
3. Sort the both parts separately by repeating step 1 and 2.
Quicksort Java Example
package com.app;
public class QuickSortTest
{
public static void main(String[] srs)
{
// This is unsorted array
Integer[] array = new Integer[] { 12, 13, 24, 10, 3, 6, 90, 70 };

// Let's sort using quick sort


quickSort( array, 0, array.length - 1 );

// Verify sorted array


System.out.println(Arrays.toString(array));
}

public static void quickSort(Integer[] arr, int low, int high)


{
//check for empty or null array
if (arr == null || arr.length == 0){
return;
}

if (low >= high){


return;
}

//Get the pivot element from the middle of the list


int middle = low + (high - low) / 2;
int pivot = arr[middle];

// make left < pivot and right > pivot


int i = low, j = high;
while (i <= j)
{
//Check until all values on left side array are lower than pivot
while (arr[i] < pivot)
{
i++;
}
//Check until all values on left side array are greater than pivot
while (arr[j] > pivot)
{
j--;
}
//Now compare values from both side of lists to see if they need swapping
//After swapping move the iterator on both lists
if (i <= j)
{
swap (arr, i, j);
i++;
j--;
}
}
//Do same operation as above recursively to sort two sub arrays
if (low < j){
quickSort(arr, low, j);
}
if (high > i){
quickSort(arr, i, high);
}
}

public static void swap (Integer array[], int x, int y)


{
int temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}

Output: [3, 6, 10, 12, 13, 24, 70, 90]


In Java, Arrays.sort() method uses quick sort algorithm to sort array of primitives using double
pivot elements. Double pivot makes this algorithm even more faster. Check that out.

==========================================================================
AES (Advanced Encryption Standard)
The Advanced Encryption Standard (AES), also known by its original name Rijndael, is a
specification for the encryption of electronic data established by the U.S. National Institute of
Standards and Technology (NIST) in 2001.
AES is a subset of the Rijndael cipher developed by two Belgian cryptographers, Joan
Daemen and Vincent Rijmen, who submitted a proposal to NIST during the AES selection
process. Rijndael is a family of ciphers with different key and block sizes.
For AES, NIST selected three members of the Rijndael family, each with a block size of 128 bits,
but three different key lengths: 128, 192 and 256 bits.
AES has been adopted by the U.S. government and is now used worldwide. It supersedes the
Data Encryption Standard (DES), which was published in 1977. The algorithm described by AES
is a symmetric-key algorithm, meaning the same key is used for both encrypting and decrypting
the data.
In the United States, AES was announced by the NIST as U.S. FIPS PUB 197 (FIPS 197) on
November 26, 2001. This announcement followed a five-year standardization process in which
fifteen competing designs were presented and evaluated, before the Rijndael cipher was
selected as the most suitable (see Advanced Encryption Standard process for more details).
AES became effective as a federal government standard on May 26, 2002 after approval by the
Secretary of Commerce. AES is included in the ISO/IEC 18033-3 standard. AES is available in
many different encryption packages, and is the first (and only) publicly accessible cipher
approved by the National Security Agency (NSA) for top secret information when used in an
NSA approved cryptographic module (see Security of AES, below).
The name Rijndael (Dutch pronunciation: [rindal]) is a play on the names of the two inventors
(Joan Daemen and Vincent Rijmen).
Java support many secure encryption algorithms but some of them are weak to be used
in security-intensive applications. For example, the Data Encryption Standard (DES) encryption
algorithm is considered highly insecure; messages encrypted using DES have been decrypted
A more secure encryption algorithm is AES Advanced Encryption Standard
which is a symmetric encryption algorithm.
AES encryption is used by U.S. for securing sensitive but unclassified material, so we can say it
is enough secure.
Example Design:

AES Example:
package com.app.aes;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESByRaghu {


private static SecretKeySpec securityKey;
private static byte[] actualKey;

public static void setKeyData(String myKey) {


MessageDigest sha_1 = null;
try {
actualKey = myKey.getBytes();
sha_1 = MessageDigest.getInstance("SHA-1");
actualKey = sha_1.digest(actualKey);
actualKey = Arrays.copyOf(actualKey, 16);
securityKey = new SecretKeySpec(actualKey, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}

public static String encryptInput(String normalStr, String secretKey) {


try {
setKeyData(secretKey);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, securityKey);
return new String(cipher.doFinal(normalStr.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public static String decryptInput(String encryptedStr, String secret) {


try {
setKeyData(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, securityKey);
return new String(cipher.doFinal(encryptedStr.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] srs) {
final String samplKey = "itisnotpassword!!";

String actualStr = "javabyraghu@gmail.com";


String encryptedString = encryptInput(actualStr, samplKey) ;
String decryptedString = decryptInput(encryptedString, samplKey) ;

System.out.println(actualStr);
System.out.println(encryptedString);
System.out.println(decryptedString);
}
}

o/p:
javabyraghu@gmail.com
#!_0_i_w_dqcT_
5X
javabyraghu@gmail.com

For More Details:


https://en.wikipedia.org/wiki/Advanced_Encryption_Standard

You might also like