Integer Sorting Algorithms - sorting

I would like to know what kind of sorting algorithm is the one below. I understand that it is a integer sorting algorithm but other than that I haven't figured it out:
void mySorter(int arr[]) {
int a = arr.length;
for (int i = 0; i < a-1; i++) {
int min = i;
for (int j = i +1 ; j < a; j++) {
if (arr[j] < arr[min])
min = j;
int temp = arr[min];
arr[min] = arr[i]
arr[i] = temp;
}
}
}
Could it be a selection sort?

It is Bubble Sort. Your code sorts the list in ascending order.

Related

array accesses in Radix Sort

I am studying radix sort and I can't understand why array accesses in radix sort is 11N+4R+1.
The following is radix sort code written in Java.
int n = a.length;
String[] aux = new String[n]; //N
int[] count = new int[R + 1]; //R+1
for (int i = 0; i < n; i++) {
count[a[i]+1]++; } //why 3N?
for (int r = 0; r < R; r++) {
count[r + 1] += count[r]; } //3R
for (int i = 0; i < n; i++) {
aux[count[a[i]]++] = a[i]; } //3N(?)+N+N = 5N
for (int i = 0; i < n; i++) {
a[i] = aux[i]; } //2N
count[a[i]+1]++; is equal to count[a[i]+1]=count[a[i]+1]+1;. I think each count[a[i]+1] has 2N array accesses so the total is 4N. If you look at the third for loop, a[i] is also duplicated at both sides in aux[count[a[i]]++] = a[i] but the right one is just counted one array access. Why does count[a[i]+1]++ count to 3N?

How to calculate this radix sorting algorithm complexity?

I have this following code. I need to calculate this algorithm complexity but i have no idea where to start. This algorithm has 3 nested loops so i guess its complexity is n^3 or am i wrong?
public static void RadixSort(DataArray data)
{
IList> digits = new List>();
for (int i = 0; i < 10; i++)
{
digits.Add(new List<int>());
}
for (int i = 0; i < data.Length; i++)
{
for (int j = 0; j < data.Length; j++)
{
int digit = (int)((data[j] % Math.Pow(10, i + 1)) / Math.Pow(10, i));
digits[digit].Add((int)data[j]);
}
int index = 0;
for (int k = 0; k < digits.Count; k++)
{
IList<int> selDigit = digits[k];
for (int l = 0; l < selDigit.Count; l++)
{
data.Swap(index++, selDigit[l]);
//data[index++] = selDigit[l];
}
}
for (int k = 0; k < digits.Count; k++)
{
digits[k].Clear();
}
}
}
Calculating complexity is more complex than just look at the number of nested loops. If you have a triple nested loop like this:
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
for(int k=0; k<n; k++)
it will be O(n³), assuming n is not changing in the loop. However, if you consider your case:
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
for(int k=0; k<m; k++)
the time complexity will instead be O(m²n).
And even the simplest sorting algorithms, like bouble sort, selection sort and insertions sort is O(n²), so if your implementation is worse than that you're doing something wrong. The time complexity for radix sort is O(wn), where w is a measure of the size of the elements.
When uncertain about complexity, a reasonable approach is to add counters to the inner-loop code and at the end of the routine print out the counts. Next, vary the size of the input to see how the results change. The empirical results can immediately confirm or deny your analytic or intuited results.

Maximum sum of non adjacent numbers in a circular array

I need to find the maximum sum of non continous subsequence, I have the following code.
public int maxSumInSubsequence(int[] data) {
if (data == null) return 0;
int n = data.length;
// maxSum[i] == the maximum sum of subsequences of data[0 .. i] that include data[i]
int[] maxSum = new int[n];
for (int i=0; i<n; ++i) {
maxSum[i] = data[i];
// maxSum[i-1] includes data[i-1] and thus cannot include data[i]
for (int j=0; j<i-1; ++j) {
maxSum[i] = Math.max(data[i] + maxSum[j], maxSum[i]);
}
}
// find the max of all subsequences
int max = 0;
for (int i=0; i<n; ++i) {
max = Math.max(max, maxSum[i]);
}
return max;
}
This works fine, but how do I modify it to exclude the first and the last element from calculation.
Iterate over the array to construct another array with starting element as the ith element and of length n-1 that wraps around the array.
Execute maxSumInSubsequence over each constructed array and find the resultant maximum.
Also, as mentioned in another answer, maxSumInSubsequence could be optimized to have O(n) time complexity.
public int maxSumInSubsequence(int[] data) {
if (data == null) return 0;
int n = data.length;
if (n <= 2) return 0;
// maxSum[i] == the maximum sum of subsequences of data[0 .. i] that include data[i]
int[] maxSum = new int[n];
for (int i=0; i<n; ++i) {
maxSum[i] = data[i];
// maxSum[i-1] includes data[i-1] and thus cannot include data[i]
for (int j=0; j<i-1; ++j) {
maxSum[i] = Math.max(data[i] + maxSum[j], maxSum[i]);
}
}
// find the max of all subsequences
int max = 0;
for (int i=0; i<n; ++i) {
max = Math.max(max, maxSum[i]);
}
return max;
}
public int maxCircularSumInSubsequence(int[] data) {
int n = data.length;
int max = 0;
for (int i = 0; i < n; i++) {
int[] circularData = new int[n-1];
for (int j = 0; j < n - 1; j++) {
circularData[j] = data[(i+j) % n];
}
max = Math.max(maxSumInSubsequence(circularData), max);
}
return max;
}
/*Function to return max sum such that no two elements
are adjacent */
int FindMaxSum(int arr[], int n)
{
int incl = arr[0];
int excl = 0;
int excl_new;
int i;
for (i = 1; i < n; i++)
{
/* current max excluding i */
excl_new = (incl > excl)? incl: excl;
/* current max including i */
incl = excl + arr[i];
excl = excl_new;
}
/* return max of incl and excl */
return ((incl > excl)? incl : excl);
}
Reference : http://www.geeksforgeeks.org/maximum-sum-such-that-no-two-elements-are-adjacent/
The basic logic is to just compute the sum for two possibilities: start i from 0 and then sum up with every alternate array no or start i with i and sum up with every alternate number from there and print the maximum of both.
arr=[5,5,10,100,10,50,1]
def max_sum_suchThatNoTwoElements_are_adjacent(arr,n,su,max_sum):
i=0
while i<n:
su+=arr[i]
if (i+1)<n:
max_sum+=arr[(i+1)]
i+=2
return max(max_sum,su)
print(max_sum_suchThatNoTwoElements_are_adjacent(arr,len(arr),0,0))

Selection Sort algorithm

Selection Sort:
I have created a selection sorting algorithm but someone said to me its not right selection sort.
If its not right so what type of sorting is it? and how it is different then selection sorting.
Code:
void selection_Sort(int arr[] , int size){
int temp , length = size;
for(int i = 0; i < size ; i++){
for(int j = i + 1; j < size ; j++){
if(arr[i] > arr[j]){
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
please tell me how can i improve it?
To transform this code into selection sort, you have to find index of minimal element in the inner cycle, and exchange element at this index with i-th element after inner cycle finishes.
So overall number of swaps does not exceed N (while your current code could produce about N^2/2 swaps)
You have implemented Bubble sort.
The selection sort means you should find the lowest(or bigest) element in inner cycle and then switch it with element to the left/right which is at the edge of selecting (like in the picture).
There are three similar sorting alghoritms - select sort, insert sort and bubble sort you can watch how they behave here : http://i.imgur.com/fq0A8hx.gif
You have to implement a minimum element after outer for loop.
Here is the code:
def selectionSort(arr):
for i in range(len(arr)):
# Find the minimum element in remaining
# unsorted array
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j]:
min_idx = j
# Swap the found minimum element with
# the first element
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
arr = [7,4,5,9,8,2,1]
print(selectionSort(arr))
How Selection sort works?
Starting from the first element, we search the smallest element in the array, and replace it with the element in the first position.
We then move on to the second position, and look for smallest element present in the subarray, starting from index 1, till the last index.
We replace the element at the second position in the original array, or we can say at the first position in the subarray, with the second smallest element.
4.This is repeated, until the array is completely sorted.
Selection Sort in Javascript
Comparing each with the rest and swapping with the smallest from the rest
Try this code here: https://repl.it/#VinitKhandelwal/selection-sort-javascript
function selectionSort(arr){
let min;
let i;
let j;
let temp;
console.log("Input Array");
console.log(arr);
for (i = 0; i < arr.length-1; i++) {
min = i;
for (j = i+1; j < arr.length; j++) {
console.log(arr[i], arr[j]);
if (arr[j] < arr[min]) {
console.log(arr[j]);
min = j;
}
}
if (min !== i) {
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
console.log(arr);
}
}
console.log("Sorted using Selection Sort");
return arr
}
console.log(selectionSort([5,7,6,9,8,2,1,4,3]));
// console.log(selectionSort([1,2,3,4,5,6,7,8,9])); // uncomment to try best case, i.e. sorted
var Selectionsort = function (A) {
for (var i = 0; i < A.length; i++) {
var imin = i;
for (var j = i + 1; j <= A.length; j++) {
if (A[j] < A[imin])
imin = j;
}
var tmp = A[i];
A[i] = A[imin];
A[imin] = tmp;
}
return A;
};
var A = [10, 20, 30, 40, 50, 60, 70, 80];
var Aftersorted = Selectionsort(A);
console.log(Aftersorted);
You can improve it this way:
void selectionSort(double array[], int size) {
int min;
double temp;
for (int step = 0; step < size-1; step++) {
min = step;
for (int i = step+1; i < size; i++) {
if (array [i] < array[min]) {
min = i;
}
}
temp = array[step];
array [step] = array[min];
array [min] = temp;
}
Selection Sort in C
Selection sort is basically selecting the very first element of your unsorted sub-array as a minimum and comparing it with the other elements of your sub-array to find your original minimum. Then, replacing that minimum element with the first element of your sub-array. That's all!
Here goes my code...
#include <stdio.h>
void selectionSort(int n){
int arr[n],i,j,minIndex;
printf("\nInsert %d elements:\n",n);
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
printf("Insert complete.\n\n");
printf("Your array looks like:\n");
for(i=0;i<n;i++){
printf("%d ",arr[i]);
}
//Selection Sort Algorithm
for(i=0;i<n-1;i++){
minIndex = i;
for(j=i+1;j<n;j++){
if(arr[j] < arr[minIndex]){
minIndex = j;
}
}
//Swapping elements
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
printf("\n\nAfter sorting your array looks like:\n");
for(i=0;i<n;i++){
printf("%d ",arr[i]);
}
}
int main(){
int n;
printf("Enter number of array elements: ");
scanf("%d",&n);
selectionSort(n);
return 0;
}
Result: -

How do I find the time complexity of these 3 nested loops?

The task is to analyze the following algorithm and calculate its time complexity.
I solved it as taking nested loops are 3 so O(n^3).
How do I solve this problem?
MSS (A[], N) //Where N is size of array A[]
{
int temp = 0, MS = 0;
For (int i = 0; i < N; i++)
{
for(int j = i; j < N; j++)
{
temp = 0;
for(int k = i; k <= j; k++)
temp = temp + A[k];
if(temp > MS)
MS = temp;
}
}
return(MS);
}
Well, you can proceed formally as such:

Resources