Skip to content

Instantly share code, notes, and snippets.

@tanaykumarbera
Created March 17, 2015 13:39
Show Gist options
  • Save tanaykumarbera/82830f88fb3ef2ff9a66 to your computer and use it in GitHub Desktop.
Save tanaykumarbera/82830f88fb3ef2ff9a66 to your computer and use it in GitHub Desktop.
Maximum

###Maximum in a List - A linear approach

MAX(array):
	
	maximum = - INFINITY /* Assign the lowest possible value */
	FOR i = 0 TO (array.length - 1)
		IF array[i] > maximum
			/* If a number greater than current maximum is encountered, */
			/* assign it as new maximum. */
			maximum = array[i]
		END IF
	END FOR

	RETURN maximum

END MAX

The loop iterates over the whole array, making it's best, average and worst an O(n).

/*
MAXIMUM in array
0 based indexing
** for TURBO C, remove // from commented statements
*/
#include<stdio.h>
//#include<conio.h>
#define INFINITY 999
int max(int *arr, int arr_length){
int i, maximum = -INFINITY;
for(i = 0; i <= arr_length - 1; i++){
if(arr[i] > maximum){
maximum = arr[i];
}
}
return maximum;
}
int main(){
int arr[10], len;
int i, maximum;
printf("\nEnter length (max 10): "); scanf("%d", &len);
printf("\nEnter %d elements one after another:\n", len);
for(i=0; i<len; i++) scanf("%d", &arr[i]);
printf("\nYour Array ::\n\t");
for(i=0; i<len; i++) printf("%d ", arr[i]);
maximum = max(arr, len);
printf("\nMaximum in this array: %d", maximum);
printf("\n");
//getch();
return 0;
}
/*
MAXIMUM in array
0 based indexing
Save File as Maximum.java
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Maximum{
public static int max(int[] arr){
/* Why static? Since we are calling from main, which itself is static */
int maximum = -999;
for(int i = 0; i <= arr.length - 1; i++){
if(arr[i] > maximum){
maximum = arr[i];
}
}
return maximum;
}
public static void main(String s[]) throws NumberFormatException, IOException{
BufferedReader ip = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter length: ");
int len = Integer.parseInt(ip.readLine());
int[] arr = new int[len];
System.out.println("\nEnter "+ len +" elements one after another:");
for(int i = 0; i < len; i++) arr[i] = Integer.parseInt(ip.readLine());
System.out.println("\nYour Array :");
for(int i = 0; i < len; i++) System.out.print(" " + arr[i]);
int maximum = max(arr);
System.out.println("\nMaximum in this array: " + maximum);
System.out.println("\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment